|
| 1 | +import { |
| 2 | + ExceptionFilter, |
| 3 | + Catch, |
| 4 | + ArgumentsHost, |
| 5 | + HttpException, |
| 6 | + HttpStatus, |
| 7 | +} from '@nestjs/common'; |
| 8 | +import { Request, Response } from 'express'; |
| 9 | +import { Logger } from '@nestjs/common'; |
| 10 | + |
| 11 | +@Catch() |
| 12 | +export class AllExceptionsFilter implements ExceptionFilter { |
| 13 | + private readonly logger = new Logger(AllExceptionsFilter.name); |
| 14 | + |
| 15 | + catch(exception: unknown, host: ArgumentsHost) { |
| 16 | + const ctx = host.switchToHttp(); |
| 17 | + const response = ctx.getResponse<Response>(); |
| 18 | + const request = ctx.getRequest<Request>(); |
| 19 | + |
| 20 | + let status = HttpStatus.INTERNAL_SERVER_ERROR; |
| 21 | + let message = 'Internal server error'; |
| 22 | + let errorResponse: any = {}; |
| 23 | + |
| 24 | + if (exception instanceof HttpException) { |
| 25 | + status = exception.getStatus(); |
| 26 | + const exceptionResponse = exception.getResponse(); |
| 27 | + if (typeof exceptionResponse === 'string') { |
| 28 | + message = exceptionResponse; |
| 29 | + } else if (typeof exceptionResponse === 'object') { |
| 30 | + errorResponse = exceptionResponse; |
| 31 | + message = (exceptionResponse as any).message || message; |
| 32 | + } |
| 33 | + } else if (exception instanceof Error) { |
| 34 | + message = exception.message; |
| 35 | + } |
| 36 | + |
| 37 | + this.logger.error(`Status: ${status} Error: ${message}`, exception instanceof Error ? exception.stack : ''); |
| 38 | + |
| 39 | + response.status(status).json({ |
| 40 | + statusCode: status, |
| 41 | + timestamp: new Date().toISOString(), |
| 42 | + path: request.url, |
| 43 | + message, |
| 44 | + ...errorResponse, |
| 45 | + }); |
| 46 | + } |
| 47 | +} |
0 commit comments