Reputation: 734
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);
Upvotes: 5
Views: 5597
Reputation: 672
You can make the exception filter request scoped
import { ExceptionFilter, Catch, ArgumentsHost, Injectable, Scope } from '@nestjs/common';
import { HttpException } from '@nestjs/common';
import { InjectConfig } from 'nestjs-config';
@Injectable({ scope: Scope.REQUEST })
@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
}
}
Now with each request new instance of the HttpExceptionFilter
gets created with its dependencies
Upvotes: 1
Reputation: 273
For the Nestjs V8, you could put this in the AppModule providers:
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},
Upvotes: 0
Reputation: 734
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
}
}
Upvotes: 1
Reputation: 9314
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);
Upvotes: 5