47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import {
|
|
ExceptionFilter,
|
|
Catch,
|
|
ArgumentsHost,
|
|
HttpException,
|
|
HttpStatus,
|
|
} from '@nestjs/common';
|
|
import { Response } from 'express';
|
|
|
|
@Catch()
|
|
export class HttpExceptionFilter implements ExceptionFilter {
|
|
catch(exception: any, host: ArgumentsHost) {
|
|
const ctx = host.switchToHttp();
|
|
const response = ctx.getResponse<Response>();
|
|
let status: HttpStatus;
|
|
let body: any;
|
|
let exceptionResponse;
|
|
|
|
try {
|
|
exceptionResponse = JSON.parse(exception.message);
|
|
} catch (error) {}
|
|
|
|
if (exception instanceof HttpException) {
|
|
if (Array.isArray(exception.getResponse()['message'])) {
|
|
exception.getResponse()['message'] = exception
|
|
.getResponse()
|
|
['message'].join(',');
|
|
}
|
|
|
|
status = exception.getStatus();
|
|
body = exception.getResponse();
|
|
} else if (typeof exceptionResponse == 'object') {
|
|
status = exceptionResponse.statusCode;
|
|
body = exceptionResponse;
|
|
} else {
|
|
status = HttpStatus.FORBIDDEN;
|
|
body = {
|
|
statusCode: HttpStatus.FORBIDDEN,
|
|
message: exception.message,
|
|
error: exception.name,
|
|
};
|
|
}
|
|
|
|
response.status(status).json(body);
|
|
}
|
|
}
|