如果应用程序级别的 useGlobalFilters 中有全局一个,为什么使用 @UseFilters(new XXXFilter()) 的 NestJS 控制器级别的 ExceptionFilter 将不起作用?

时间:2021-02-05 16:22:32

标签: javascript exception nestjs httpexception nestjs-config

我定义了两个自定义 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'
    });
  }
}

0 个答案:

没有答案
相关问题