How to inject Logger Service into exception filters

I’m working on a NestJS application and trying to inject my logger service into an ExceptionFilter. Here’s my code:

export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly loggerService: LoggerService) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    this.loggerService.log(exception.message, 'error');

I’ve registered the HttpExceptionFilter & LoggerService in my AppModule like this:

  providers: [
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
export class AppModule {}

However, when the catch method of the HttpExceptionFilter is executed, I’m getting the following error:

TypeError: Cannot read properties of undefined (reading ‘log’)

>Solution :

in your main file add

  const loggerService = await app.resolve(LoggerService);

    new HttpExceptionFilter(loggerService),

Leave a Reply