我定义了两个自定义HttpExceptionFilter
的,一个用于全局,一个用于控制器 api 级别。但是当我调试时,我发现总是会跳过一级控制器。有没有办法让这两个过滤器都起作用?因为我想在某些控制器端点中的 http 失败或抛出特定控制器的特定 http 异常时进一步自定义和添加额外的错误代码。
这甚至可以使用 NestJS 吗?有替代方案吗?我做错了吗?
在全球范围内:
app.useGlobalFilters(new HttpExceptionFilter(), new ConflictErrorFilter());
在控制器中:
@UseFilters(new ControllerHttpExceptionFilter())
@UseInterceptors(ClassSerializerInterceptor)
@Post('/:id/dothing')
....
CustomException 过滤器和 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'
});
}
}