import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'; import { FastifyReply } from 'fastify'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { // Handle HTTP/REST context try { const ctx = host.switchToHttp(); const reply = ctx.getResponse(); // Safety check: ensure reply has the status method if (!reply || typeof reply.status !== 'function') { return; } // const request = ctx.getRequest(); const status = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR; const exceptionResponse = exception.getResponse(); const message = this.extractMessage(exceptionResponse); reply.status(status).send({ statusCode: status, success: false, error: { message, // timestamp: new Date().toISOString(), // path: request.url, }, }); } catch { // If we can't handle it, let it propagate return; } } private extractMessage(response: string | Record): string | string[] { if (typeof response === 'string') { return [response]; } if (typeof response === 'object' && 'message' in response) { return Array.isArray(response.message) ? response.message : [response.message]; } return 'something wrong'; } }