You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS拦截器的catchError中捕获异常并返回正确状态码

问题:NestJS日志拦截器导致异常响应状态码变为200

我正在开发一个日志拦截器,用于记录API的所有HTTP请求。正常流程下一切运行正常,但当控制器抛出400状态的异常并经过拦截器后,Postman收到的响应状态码却是200,响应体中包含异常信息。我已阅读NestJS官方文档并尝试在拦截器类中使用相关方法,但尝试多种方式后出现不同错误。请问如何实现既能返回所需状态码,又能让请求经过拦截器的方案?

以下是我的拦截器代码:

@Injectable()
export class LogsInterceptor<T> implements NestInterceptor<T> {
  constructor(
    private logService: LogsService,
    private jwtService: JwtService,
  ) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> {
    const request = context.switchToHttp().getRequest();
    let responseStatus = context.switchToHttp().getResponse();
    let log: ILogModel;
    let id: number;
    let args: any = context.getArgs()[0];

    console.log('before');
    return next.handle().pipe(
      map(async (data) => {
        id = this.setId(args, id, data);
        log = {
          ip: args.hostname,
          id,
          tipo: args.method,
          path: args.originalUrl,
          query: args.query,
          params: args.params,
          body: args.body,
          token: args.headers.authorization,
          response: data,
          statuscode: responseStatus.statusCode,
        };
        let idT: number = 0;
        idT = await this.logRequest(log);
        console.log(args.route.path);
        let respuestaF = {};
        if (
          args.route.path == '/cards/:pan' ||
          args.route.path == '/cards/:pan/paymentRequest'
        ) {
          delete data[0].code;
          delete data[0].solicitud;
          respuestaF = {
            requestId: idT,
            message: data[0].message,
            companyid: data[0].companyid,
            expirationdate: data[0].expirationdate,
            licenseplate: data[0].licenseplate,
          };
        } else {
          respuestaF = {
            requestId: idT,
            data,
          };
        }
        console.log('after');
        return respuestaF;
      }),
      catchError(async (error: any) => {
        console.log(request.statusCode);
        console.log(responseStatus.statusCode);
        id = this.setId(args, id, error);
        log = {
          ip: args.hostname,
          id,
          tipo: args.method,
          path: args.originalUrl,
          query: args.query,
          params: args.params,
          body: args.body,
          token: args.headers.authorization,
          response: error,
          statuscode: error.status,
        };
        let idT: number = 0;
        idT = await this.logRequest(log);
        let respuestaF = {
          requestId: idT,
          error,
        };
        // if (error instanceof HttpException) {
        //   console.log('httpexcpcion');
        //   return throwError(
        //     () => new HttpException(respuestaF, HttpStatus.BAD_REQUEST),
        //   );
        // }
        console.log(log);
        console.log(responseStatus.statusCode);
        console.log('entrado por error');
        return respuestaF;
      }),
    );
  }
}

当前响应状态码为200,响应体包含异常信息,如图所示:
响应状态码异常示例

内容的提问来源于stack exchange,提问作者tsiPlus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:53:34