Last active
December 22, 2021 03:30
-
-
Save jasonbyrne/1b42387e4a38d75f3ddc6a9db41f2707 to your computer and use it in GitHub Desktop.
Nest JS Exception Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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