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

Nestjs自定义异常过滤器报错:applicationRef.isHeadersSent不是函数

NestJS自定义异常过滤器继承BaseExceptionFilter报错问题

我在开发继承NestJS BaseExceptionFilter的自定义异常过滤器时遇到问题。尝试注入HttpAdapterHost为BaseExceptionFilter构造函数提供applicationRef参数,但调用super.catch时出现报错:applicationRef.isHeadersSent is not a function。当前ApplicationRef是有效对象,但确实没有isHeadersSent方法,不清楚原因,想了解如何正确构建这类自定义过滤器,官方文档表明这是可行的。

问题代码

import {
  ArgumentsHost,
  Catch,
  HttpException,
  Injectable,
} from '@nestjs/common';
import { BaseExceptionFilter, HttpAdapterHost } from '@nestjs/core';
import { Response } from 'express';
import { StructuredLogger } from './structured-logger.service';

// Catch any non-http exception and log it nicely with context instead of directly printing to stderr
@Catch()
@Injectable()
export class UncaughtExceptionFilter extends BaseExceptionFilter {
  logger: StructuredLogger;

  constructor(
    readonly baseLogger: StructuredLogger,
    private adapterHost: HttpAdapterHost,
  ) {
    const instance = adapterHost.httpAdapter.getInstance();
    super(instance);
    this.logger = baseLogger.forClass('UncaughtExceptionFilter', 'uncaught');
  }

  catch(exception: any, host: ArgumentsHost) {
    if (exception instanceof HttpException) {
      super.catch(exception, host);
    } else {
      this.logger.error(exception, 'Uncaught exception', {});
      //Respond manually to avoid printing to stderr
      const ctx = host.switchToHttp();
      const response = ctx.getResponse<Response>();
      const status = 500;
      response.status(status).json({
        statusCode: status,
        message: 'Internal server error',
      });
    }
  }
}

解决方案

问题根源是传给父类构造函数的参数错误。BaseExceptionFilter需要的是HttpAdapter实例,而非getInstance()返回的底层框架(如Express)原生app对象。原生对象没有Nest封装的isHeadersSent等方法,导致报错。

修改构造函数,直接传入adapterHost.httpAdapter即可:

constructor(
  readonly baseLogger: StructuredLogger,
  private adapterHost: HttpAdapterHost,
) {
  super(adapterHost.httpAdapter); // 直接传递HttpAdapter实例
  this.logger = baseLogger.forClass('UncaughtExceptionFilter', 'uncaught');
}

额外说明

  • 全局注册过滤器时,确保正确注入依赖:
    在main.ts中:
    const app = await NestFactory.create(AppModule);
    const logger = app.get(StructuredLogger);
    const httpAdapterHost = app.get(HttpAdapterHost);
    app.useGlobalFilters(new UncaughtExceptionFilter(logger, httpAdapterHost));
    
    或者在模块中通过providers配置全局过滤器:
    @Module({
      providers: [
        {
          provide: APP_FILTER,
          useClass: UncaughtExceptionFilter,
        },
      ],
    })
    export class AppModule {}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 01:42:08