|
| 1 | +import { |
| 2 | + ArgumentsHost, |
| 3 | + Catch, |
| 4 | + ExceptionFilter, |
| 5 | + HttpException, |
| 6 | + HttpStatus, |
| 7 | + Logger, |
| 8 | +} from '@nestjs/common'; |
| 9 | +import { Response, Request } from 'express'; |
| 10 | + |
| 11 | +@Catch() |
| 12 | +export class HttpExceptionFilter implements ExceptionFilter { |
| 13 | + private readonly logger = new Logger(HttpExceptionFilter.name); |
| 14 | + |
| 15 | + constructor(private readonly isProduction = false) {} |
| 16 | + |
| 17 | + catch(exception: unknown, host: ArgumentsHost) { |
| 18 | + const ctx = host.switchToHttp(); |
| 19 | + const response = ctx.getResponse<Response>(); |
| 20 | + const request = ctx.getRequest<Request>(); |
| 21 | + |
| 22 | + const isHttp = exception instanceof HttpException; |
| 23 | + const status = isHttp |
| 24 | + ? exception.getStatus() |
| 25 | + : HttpStatus.INTERNAL_SERVER_ERROR; |
| 26 | + |
| 27 | + const errorResponse = isHttp |
| 28 | + ? exception.getResponse() |
| 29 | + : { message: (exception as Error)?.message }; // fallback message |
| 30 | + |
| 31 | + const { message, error } = this.normalizeResponse(errorResponse, exception); |
| 32 | + |
| 33 | + const payload = { |
| 34 | + statusCode: status, |
| 35 | + message, |
| 36 | + error, |
| 37 | + timestamp: new Date().toISOString(), |
| 38 | + path: request.url, |
| 39 | + }; |
| 40 | + |
| 41 | + this.logger.error( |
| 42 | + ${status} -> , |
| 43 | + (exception as Error)?.stack, |
| 44 | + ); |
| 45 | + |
| 46 | + if (!this.isProduction && exception instanceof Error) { |
| 47 | + Object.assign(payload, { stack: exception.stack }); |
| 48 | + } |
| 49 | + |
| 50 | + response.status(status).json(payload); |
| 51 | + } |
| 52 | + |
| 53 | + private normalizeResponse( |
| 54 | + response: string | object | null | undefined, |
| 55 | + exception: unknown, |
| 56 | + ) { |
| 57 | + let message = 'Internal server error'; |
| 58 | + let error = HttpStatus.INTERNAL_SERVER_ERROR.toString(); |
| 59 | + |
| 60 | + if (typeof response === 'string') { |
| 61 | + message = response; |
| 62 | + } else if (response && typeof response === 'object') { |
| 63 | + const body = response as Record<string, any>; |
| 64 | + if (body.message) { |
| 65 | + message = Array.isArray(body.message) |
| 66 | + ? body.message.join(', ') |
| 67 | + : body.message; |
| 68 | + } else if (exception instanceof Error && exception.message) { |
| 69 | + message = exception.message; |
| 70 | + } |
| 71 | + |
| 72 | + if (body.error) { |
| 73 | + error = body.error; |
| 74 | + } |
| 75 | + } else if (exception instanceof Error) { |
| 76 | + message = exception.message; |
| 77 | + } |
| 78 | + |
| 79 | + return { message, error }; |
| 80 | + } |
| 81 | +} |
0 commit comments