Files
negareh-api/src/core/exceptions/http.exceptions.ts
T
2026-01-07 12:13:45 +03:30

49 lines
1.4 KiB
TypeScript
Executable File

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<FastifyReply>();
// Safety check: ensure reply has the status method
if (!reply || typeof reply.status !== 'function') {
return;
}
// const request = ctx.getRequest<FastifyRequest>();
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, any>): 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';
}
}