When it comes to using express and typescript, I am attempting to create a middleware for error handling similar to Sentry. Below is the code snippet:
const catchError = (
error: Error,
req: Request,
_res: Response,
next: any
) => {
console.log("ERROR: ", error);
//some logic
next(error);
}
In my index.ts file:
app.use(bodyParser.json({ limit }));
app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));
app.use(express.json());
app.use(cors({ credentials: true, origin: true }));
app.use(bodyParser.urlencoded({ extended: false }));
//controllers
app.use(catchError as express.ErrorRequestHandler)
I'm wondering why my middleware only works when I include this:
} catch (error) {
next(error);
}
inside the function where the error occurs, and it does not work without it. Can this middleware handle errors and exceptions without using next(error)
?
Any help would be greatly appreciated!