Skip to content

Instantly share code, notes, and snippets.

@richardfeliciano
Created November 17, 2024 11:41
Show Gist options
  • Save richardfeliciano/402d49337588fb5623bcf87625c3c067 to your computer and use it in GitHub Desktop.
Save richardfeliciano/402d49337588fb5623bcf87625c3c067 to your computer and use it in GitHub Desktop.
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';
interface ErrorObject {
[key: string]: {
message: string;
};
}
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost): void {
const context = host.switchToHttp();
const response = context.getResponse<Response>();
const request = context.getRequest<Request>();
const status = exception.getStatus();
const exceptionResponse = exception.getResponse();
const message = exception.message;
const errors = this.parseErrors(exceptionResponse);
const errorResponse = this.createErrorResponse(
status,
message,
errors,
request.url,
exception.stack
);
response.status(status).json(errorResponse);
}
private parseErrors(response: unknown): ErrorObject {
const errors = this.extractMessage(response);
return this.convertArrayToObject(errors);
}
private extractMessage(response: any): any[] {
if (typeof response === 'string') return [];
return response?.message || [];
}
private convertArrayToObject(input: any[]): ErrorObject {
return input.reduce((acc, { property, message }) => {
acc[property] = { message };
return acc;
}, {} as ErrorObject);
}
private createErrorResponse(
status: number,
message: string,
errors: ErrorObject,
path: string,
trace?: string
): Record<string, any> {
const baseResponse = {
message,
errors,
timestamp: new Date().toISOString(),
};
if (process.env.NODE_ENV === 'development') {
return {
...baseResponse,
path,
trace,
};
}
return baseResponse;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment