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

Nest.js中@Inject装饰器属性注入异常过滤器失效求助

问题原因

你遇到的smsService为undefined的问题,根源在于重复注册全局过滤器且其中一个实例未被Nest依赖注入容器管理:

  • 你已经在AppModule的providers中通过APP_FILTER令牌注册了InternalServerErrorFilter,此时Nest会自动为该过滤器注入所需依赖。
  • 但你又在main.ts中通过app.useGlobalFilters(new InternalServerErrorFilter())手动创建了一个过滤器实例,这个实例不在Nest的DI容器管控范围内,因此@Inject(SmsService)不会生效,导致smsService未被初始化。
解决方案

只需保留一种全局过滤器的注册方式即可,以下是两种可行方案:

方案一:移除main.ts中的手动注册

直接删除main.ts里的手动注册代码,依赖AppModule中通过APP_FILTER的注册方式,Nest会自动处理依赖注入:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 移除该行:app.useGlobalFilters(new InternalServerErrorFilter());
  await app.listen(3000);
}
bootstrap();

方案二:从DI容器获取过滤器实例(保留main.ts注册)

如果需要在main.ts中注册全局过滤器,不要手动new实例,而是从Nest容器中获取已完成依赖注入的实例:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const errorFilter = app.get(InternalServerErrorFilter);
  app.useGlobalFilters(errorFilter);
  await app.listen(3000);
}
bootstrap();

这种方式下,errorFilter是由Nest容器管理的实例,其中的smsService会被正确注入。

额外优化建议
  • 给异常过滤器类添加@Injectable()装饰器,虽然通过APP_FILTER注册时Nest会自动识别,但显式添加能保证语义完整:
@Injectable()
@Catch(InternalServerErrorException)
export class InternalServerErrorFilter implements ExceptionFilter {
  // ... 现有代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:45:30