Search code examples
exceptionerror-handlingnestjsnestjs-exception-filters

Is there a way to have Nest use the ExceptionsHandler error message as the API response message when an exception is thrown?


When an error is thrown within my Nest API, often times the error that is thrown is not an HttpException, and therefore the standard Nest API response that I see from the client's side is:

{
  "statusCode": 500,
  "message": "Internal server error"
}

But when I look at the console log, there is a much more descriptive error message, for example:

[Nest] 18476  - 06/23/2022, 2:28:07 PM   ERROR [ExceptionsHandler] Cannot perform update query 
because update values are not defined.
UpdateValuesMissingError: Cannot perform update query because update values are not defined. 

Is there a way I can route this message to be the in the response body of the response given back to the API client?


Solution

  • You can use Global Filter in NestJs to catch error and then throw a good error.

    For exemple, you can create a Exception Filter

    // UpdateValuesMissingError.exception-filter.ts
    import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
    import { Request, Response } from 'express';
    
    @Catch(UpdateValuesMissingError)
    export class UpdateValuesMissingErrorFilter implements ExceptionFilter {
      catch(exception: UpdateValuesMissingError, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
    
        console.log(exception);
    
        response.status(400).json({
          statusCode: 400,
          timestamp: new Date().toISOString(),
          path: request.url,
        });
      }
    }
    
    

    and in your main.ts add this

    app.useGlobalFilters(new HttpExceptionFilter());

    And now in response.status(400).json({}) you can add everything you want in your body. Like the error message of Axios.