lecoffre-back/src/app/middlewares/ErrorHandler.ts
2024-01-02 17:52:22 +01:00

38 lines
1.0 KiB
TypeScript

import HttpException from "@Common/system/controller-pattern/exceptions/HttpException";
import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
import { NextFunction, Request, Response } from "express";
import * as Sentry from "@sentry/node";
export default function errorHandler(error: any, req: Request, response: Response, next: NextFunction) {
const errorStatus: number = error["status"];
/**
* Used on when try to parse json on request
*/
if (error instanceof SyntaxError && errorStatus === 400 && "body" in error) {
response.status(HttpCodes.BAD_REQUEST).send({
body: error["body"],
type: error as any["type"],
});
return;
}
const transaction = Sentry.startTransaction({
op: "Crashed Application",
name: "Crashed Application",
});
if (error instanceof Error) {
Sentry.captureException(error.stack);
} else {
Sentry.captureException(error);
}
transaction.finish();
if (error instanceof HttpException) {
response.status(error.httpCode).send(error.message);
return;
}
next(error);
}