Skip to content

Instantly share code, notes, and snippets.

@jasonbyrne
Last active December 22, 2021 03:30
Show Gist options
  • Save jasonbyrne/1b42387e4a38d75f3ddc6a9db41f2707 to your computer and use it in GitHub Desktop.
Save jasonbyrne/1b42387e4a38d75f3ddc6a9db41f2707 to your computer and use it in GitHub Desktop.
Nest JS Exception Handler
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Response } from 'express';
import { IncomingMessage } from 'http';
import { HttpException, HttpStatus } from '@nestjs/common';
export const getStatusCode = (exception: unknown): number => {
return exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
};
export const getErrorMessage = (exception: unknown): string => {
return String(exception);
};
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<IncomingMessage>();
const code = getStatusCode(exception);
const message = getErrorMessage(exception);
response.status(status).json({
error: {
timestamp: new Date().toISOString(),
path: request.url,
code,
message
},
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment