简体   繁体   English

在 Nestjs 的过滤器中注入服务

[英]inject services inside filters in nestjs

I'm trying to inject nestjs-config inside the following exception handler i've created:我正在尝试在我创建的以下异常处理程序中注入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
  }
}

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

this is how the exception handler is defined globally:这是异常处理程序的全局定义方式:

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

Ok so I've just realised that in your code you're creating the filter outside of the container therefore the ConfigService is not injected.好的,我刚刚意识到在您的代码中您正在容器外部创建过滤器,因此未注入 ConfigService。 There's a few ways to resolve this.有几种方法可以解决这个问题。 One

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

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

Or或者

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

Depending that your AppModule looks like this取决于你的 AppModule 看起来像这样

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

Or like this:或者像这样:

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

solved it by calling the ConfigService as follows:通过调用 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
  }
}

For the Nestjs V8, you could put this in the AppModule providers:对于 Nestjs V8,您可以将其放在 AppModule 提供程序中:

{
  provide: APP_FILTER,
  useClass: HttpExceptionFilter,
},

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

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