繁体   English   中英

在 Nestjs 的过滤器中注入服务

[英]inject services inside filters in nestjs

我正在尝试在我创建的以下异常处理程序中注入nestjs-config

import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common';
import { HttpException } from '@nestjs/common';
import { InjectConfig } from 'nestjs-config';

@Injectable()
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @InjectConfig()
    private readonly config,
  ) {
    this.config = config.get('errors');
  }
  catch(exception: HttpException, host: ArgumentsHost) {
    // some code here that calls this.config
  }
}

但它返回未定义:类型错误TypeError: Cannot read property 'get' of undefined

这是异常处理程序的全局定义方式:

const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);

好的,我刚刚意识到在您的代码中您正在容器外部创建过滤器,因此未注入 ConfigService。 有几种方法可以解决这个问题。

ConfigService.load(path.resolve(__dirname, 'config', '*.ts'))

const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalFilters(new HttpExceptionFilter(ConfigService));
await app.listen(3000);

或者

const app = await NestFactory.create(AppModule, {cors: true});
const config = app.get<ConfigService>(ConfigService);
app.useGlobalFilters(new HttpExceptionFilter(config));
await app.listen(3000);

取决于你的 AppModule 看起来像这样

@Module({
    imports: [ConfigModule.load(path.resolve(__dirname, 'config', '*.ts')],
})
export AppModule {}

或者像这样:

const app = await NestFactory.create(AppModule, {cors: true});
const httpExceptionFilter = app.get(HttpExpectionFilter);
app.useGlobalFilters(httpExpectionFilter);

通过调用 ConfigService 来解决它,如下所示:

export class HttpExceptionFilter implements ExceptionFilter {

  constructor(private readonly config: ConfigService) {
    this.config = ConfigService.get('errors');
  }
  catch(exception: HttpException, host: ArgumentsHost) {
    // some code here that calls this.config
  }
}

对于 Nestjs V8,您可以将其放在 AppModule 提供程序中:

{
  provide: APP_FILTER,
  useClass: HttpExceptionFilter,
},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM