0

I defined two custom HttpExceptionFilter one used in global and one in controller api level. But when I debug I found that controller level one will always be skipped. Is there way we can allow both filter functional? Because I want to further customize and add additional error codes when http failed in certain controller endpoints or with specific http exception for a specific controller when thrown.

Is this even possible using NestJS? Is there an alternative? Am I approach this wrong?

In global:

app.useGlobalFilters(new HttpExceptionFilter(), new ConflictErrorFilter());

In controller:

@UseFilters(new ControllerHttpExceptionFilter())
  @UseInterceptors(ClassSerializerInterceptor)
  @Post('/:id/dothing')
....

CustomException Filter and ControllerHttpExceptionFilter

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost): void {
    const response = host.switchToHttp().getResponse<FastifyReply>();
    const { statusCode, error, message } = exception.getResponse() as Record<
      string,
      any
    >;

    void response.status(statusCode).send({
      status_code: statusCode,
      message: [].concat(message),
      error,
      error_code: 'PLAYROUND'
    });
  }
}


@Catch(HttpException)
export class ControllerHttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost): void {
    const response = host.switchToHttp().getResponse<FastifyReply>();
    const resp = exception.getResponse();
    const { statusCode, error, message } = resp as Record<
      string,
      any
    >;

    void response.status(statusCode).send({
      status_code: statusCode,
      message: [].concat(message),
      error,
      error_code: 'PLAYROUND controller'
    });
  }
}
ey dee ey em
  • 7,991
  • 14
  • 65
  • 121
  • Odd, the [documentation states](https://docs.nestjs.com/faq/request-lifecycle#filters) that filters resolve in order of route handler to controller to global. – Jay McDoniel Feb 05 '21 at 17:18
  • @JayMcDoniel I added the relevant code, do u see any issue how I wrote it? – ey dee ey em Feb 05 '21 at 17:50
  • 1
    when the first filter already catches the exception and returns the response(no error/exception), will the second one will have an error to catch? I am not sure but if you want both to execute try throwing the exception back from the first one. – AZ_ Feb 06 '21 at 07:27

0 Answers0