javascripttypescriptnestjsfastifynestjs-config

How to write the response from nestjs exception filters using nestfastify


I have an issue in writing custom http response from nestjs exception filters
I'm using the nest fastify one (not the express)
I'm creating custom exception filters that catch UserNotFoundException as follows:

@Catch(UserNotFoundException)
export class UserNotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: UserNotFoundException, host: ArgumentsHost) {
    const errorResponse = new ErrorResponse<string[]>();
    const response = host.switchToHttp().getResponse();
    errorResponse.message = 'unauthorized exception'
    errorResponse.errors = [
      'invalid username or pass'
    ];
    response.status(401).json(errorResponse)

  }
}

i keep getting response.status(...).json() is not a function.

[Nest] 5400   - 05/17/2020, 00:27:26   [ExceptionsHandler] response.status(...).json is not a function +82263ms
TypeError: response.status(...).json is not a function

I know that i had to specify the type of that response to some type of response writer (e.g : Response from express).

i try to import that Response object from express, and update type of response variable to Response(express) like following:

import {Response} from 'express';
 const response = host.switchToHttp().getResponse<Response>();

and everything running smoothly.

But i dont want to add some express thing to my application, i just want to go with nestjs fastify. Do you guys know any class that can replace this Response obejct from express? Or if you another smarter way to tackle this, it will help also

thank everyone


Solution

  • If you are using Fastify you need to use the FastifyReply<ServerResponse> type from fastify and the http packages. Fastify itself does not have a json method on the reply object, but it does have a .send() method that will JSON.stringify() an object if it is given an object.

    While the project may build if you use the Response object from express, you'll probably get a runtime error about response.status().json is not a function. The below should work properly

    import { FastifyReply } from 'fastify';
    
    @Catch(UserNotFoundException)
    export class UserNotFoundExceptionFilter implements ExceptionFilter {
      catch(exception: UserNotFoundException, host: ArgumentsHost) {
        const errorResponse = new ErrorResponse<string[]>();
        const response = host.switchToHttp().getResponse<FastifyReply<ServerResponse>>();
        errorResponse.message = 'unauthorized exception'
        errorResponse.errors = [
          'invalid username or pass'
        ];
        response.status(401).send(errorResponse)
    
      }
    }
    

    Overall, Nest is a wrapper for Express and Fastify, and most of the docs are pertinent to Express when talking about library specific options (like Request and Response). You should reference Fastify's documentation when it comes to library specific approaches.