|
import { |
|
ArgumentsHost, |
|
Catch, |
|
ExceptionFilter, |
|
HttpException, |
|
HttpStatus, |
|
} from '@nestjs/common'; |
|
import { Request, Response } from 'express'; |
|
|
|
import { VERSION } from '../version'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
export function serializeError(err: unknown) { |
|
const properties = Object.getOwnPropertyNames(err); |
|
|
|
properties.push('name'); |
|
return JSON.parse(JSON.stringify(err, properties)); |
|
} |
|
|
|
@Catch() |
|
export class AllExceptionsFilter implements ExceptionFilter { |
|
catch(exception: any | Error, host: ArgumentsHost): void { |
|
const ctx = host.switchToHttp(); |
|
const response = ctx.getResponse<Response>(); |
|
const request = ctx.getRequest<Request>(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (exception.code === 'ENOENT') { |
|
response.status(HttpStatus.NOT_FOUND).json({ |
|
error: { |
|
code: 404, |
|
key: 'FILE_NOT_FOUND', |
|
message: 'File not found', |
|
details: 'File not found or no longer available', |
|
}, |
|
}); |
|
response.send(); |
|
return; |
|
} |
|
|
|
|
|
|
|
|
|
if (exception instanceof HttpException) { |
|
response.status(exception.getStatus()).json(exception.getResponse()); |
|
return; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
const httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; |
|
response.status(httpStatus).json({ |
|
statusCode: httpStatus, |
|
timestamp: new Date().toISOString(), |
|
exception: serializeError(exception), |
|
request: { |
|
path: request.url, |
|
method: request.method, |
|
body: request.body, |
|
query: request.query, |
|
}, |
|
version: VERSION, |
|
}); |
|
} |
|
} |
|
|