简体   繁体   中英

inject services inside filters in nestjs

I'm trying to inject nestjs-config inside the following exception handler i've created:

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

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. 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

@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:

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:

{
  provide: APP_FILTER,
  useClass: HttpExceptionFilter,
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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