Skip to content

Instantly share code, notes, and snippets.

@Mualig
Last active February 15, 2022 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mualig/533f1ff4810aaa317adf2cde4af45596 to your computer and use it in GitHub Desktop.
Save Mualig/533f1ff4810aaa317adf2cde4af45596 to your computer and use it in GitHub Desktop.
NestJS Exception logger filter
import { ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { Constants } from '../constants.utils';
import { LoggingService } from '../logging/logging.service';
@Catch()
export class ExceptionsLoggerFilter extends BaseExceptionFilter {
private readonly log;
constructor(logger: LoggingService, httpAdapter: any) {
super(httpAdapter);
this.log = logger.getLogger('ExceptionsLoggerFilter');
}
catch(exception: unknown, host: ArgumentsHost) {
const uuid: string = host.switchToHttp().getRequest().headers[Constants.correlationId];
if (exception instanceof HttpException) {
this.log.warn({ uuid }, `${exception}`);
} else {
this.log.error({ uuid }, `${exception}`);
}
super.catch(exception, host);
}
}
...
async function bootstrap() {
...
// Use our logger for all Nest logs
const logger = await app.resolve(LoggingService);
app.useLogger(logger);
const { httpAdapter } = app.get(HttpAdapterHost);
app.useGlobalFilters(new ExceptionsLoggerFilter(logger, httpAdapter));
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment