Skip to content

Instantly share code, notes, and snippets.

@paulozullu
Created November 4, 2021 14:05
Show Gist options
  • Save paulozullu/b75ed03f1509dfe9476d7701a28fc4c3 to your computer and use it in GitHub Desktop.
Save paulozullu/b75ed03f1509dfe9476d7701a28fc4c3 to your computer and use it in GitHub Desktop.
NestJS Exceptions Filter
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private logger = new Logger(AllExceptionsFilter.name);
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof HttpException
? exception.getResponse()
: exception['message'];
this.logger.error(
`Http Status: ${status} Error message: ${JSON.stringify(message)}`,
);
response.status(status).json({
timestamp: new Date().toISOString(),
path: request.url,
error: message,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment