#Best practices for error handling in node js
8 messages · Page 1 of 1 (latest)
Depends on what you're doing, but a global try/catch in your async chain is a good starting point.
A single try/catch for each route correct at the start
No, make an error handler earlier in the chain
Just the one.
If you have external things that can throw their own errors handle those in your service, not in the route handler.
No like one try catch at start of the chain for each service or middleware
I use this to wrap my middleware functions:
export const asyncHandler = (fn) => (req, res, next) => {
fn(req, res, next).catch((e) => {
const error = new Error(e.message);
error.statusCode = (e.response?.status || e.statusCode) ?? 500;
next(error);
});
};
usage:
router.get('/pathways', asyncHandler(getPathwaysData));