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'
});
}
}