mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-15 02:15:21 +00:00
Refactor HttpExceptionFilter to unify the error response
This commit is contained in:
@ -5,34 +5,55 @@ import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const request = ctx.getRequest<Request>();
|
||||
const status =
|
||||
exception instanceof HttpException
|
||||
? exception.getStatus()
|
||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
const message =
|
||||
exception instanceof HttpException
|
||||
? exception.getResponse()
|
||||
: 'Internal server error';
|
||||
const status = this.getStatus(exception);
|
||||
const errorMessage = this.getErrorMessage(exception);
|
||||
const formattedStatus = this.formatStatus(status);
|
||||
|
||||
const errorResponse = {
|
||||
statusCode: status,
|
||||
timestamp: new Date().toISOString(),
|
||||
path: request.url,
|
||||
error: message,
|
||||
error:
|
||||
typeof errorMessage === 'string'
|
||||
? {
|
||||
message: errorMessage,
|
||||
error: formattedStatus,
|
||||
statusCode: status,
|
||||
}
|
||||
: errorMessage,
|
||||
};
|
||||
|
||||
// Optionally log the exception
|
||||
console.error(`Error occurred:`, exception);
|
||||
|
||||
console.error('Error occurred:', exception);
|
||||
response.status(status).json(errorResponse);
|
||||
}
|
||||
|
||||
private getStatus(exception: unknown): HttpStatus {
|
||||
return exception instanceof HttpException
|
||||
? exception.getStatus()
|
||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
|
||||
private getErrorMessage(exception: unknown): string | object {
|
||||
return exception instanceof HttpException
|
||||
? exception.getResponse()
|
||||
: 'Internal server error';
|
||||
}
|
||||
|
||||
private formatStatus(status: HttpStatus): string {
|
||||
return HttpStatus[status]
|
||||
.toLowerCase()
|
||||
.replace('_', ' ')
|
||||
.split(' ')
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user