Created
November 4, 2021 14:05
-
-
Save paulozullu/b75ed03f1509dfe9476d7701a28fc4c3 to your computer and use it in GitHub Desktop.
NestJS Exceptions Filter
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 { | |
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