Files
twenty/packages/twenty-server/src/utils/apply-cors-to-exceptions.ts
martmull 4fcdfbff7d Fix unhandled exception (#5474)
Solves exception.getStatus is not a function error logs in twenty-server

Catch all errors in order to have no error log at all
2024-05-21 11:31:03 +02:00

39 lines
1.1 KiB
TypeScript

import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
} from '@nestjs/common';
import { Response } from 'express';
// In case of exception in middleware run before the CORS middleware (eg: JSON Middleware that checks the request body),
// the CORS headers are missing in the response.
// This class add CORS headers to exception response to avoid misleading CORS error
@Catch()
export class ApplyCorsToExceptions implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
if (!response.header) {
return;
}
response.header('Access-Control-Allow-Origin', '*');
response.header(
'Access-Control-Allow-Methods',
'GET,HEAD,PUT,PATCH,POST,DELETE',
);
response.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
const status =
exception instanceof HttpException ? exception.getStatus() : 500;
response.status(status).json(exception.response);
}
}