import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus, Logger, } from '@nestjs/common'; import { Response } from 'express'; import { AppError, ErrorCode } from '../errors/app.error'; interface ErrorResponse { statusCode: number; message: string; code: ErrorCode; timestamp: string; path: string; } @Catch(AppError) export class AppExceptionFilter implements ExceptionFilter { private readonly logger = new Logger(AppExceptionFilter.name); catch(exception: AppError, host: ArgumentsHost): void { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const status = this.getHttpStatus(exception.code); this.logger.error( `[${exception.code}] ${exception.message}`, JSON.stringify({ context: exception.context, timestamp: exception.timestamp, path: request.url, }), ); const errorResponse: ErrorResponse = { statusCode: status, message: exception.message, code: exception.code, timestamp: exception.timestamp.toISOString(), path: request.url, }; response.status(status).json(errorResponse); } private getHttpStatus(code: ErrorCode): number { const statusMap: Record = { [ErrorCode.VALIDATION_ERROR]: HttpStatus.BAD_REQUEST, [ErrorCode.FILE_PROCESSING_ERROR]: HttpStatus.BAD_REQUEST, [ErrorCode.HAR_PARSE_ERROR]: HttpStatus.UNPROCESSABLE_ENTITY, [ErrorCode.SWAGGER_GENERATION_ERROR]: HttpStatus.INTERNAL_SERVER_ERROR, [ErrorCode.AI_SERVICE_ERROR]: HttpStatus.SERVICE_UNAVAILABLE, [ErrorCode.INTERNAL_ERROR]: HttpStatus.INTERNAL_SERVER_ERROR, }; return statusMap[code] || HttpStatus.INTERNAL_SERVER_ERROR; } }