Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

@Catch(HttpException)
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:

@Module({
  providers: [
    LoggerService,
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})
export class AppModule {}

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

in your main file add


  const loggerService = await app.resolve(LoggerService);

  app.useGlobalFilters(
    new HttpExceptionFilter(loggerService),
  );

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading