#Best practices for error handling in node js

8 messages · Page 1 of 1 (latest)

ripe aurora
#

How do you handle error in node js do you guys use nested try catch for everything or .then().catch() with callback hell or is there a better way?

wide palm
#

Depends on what you're doing, but a global try/catch in your async chain is a good starting point.

ripe aurora
#

A single try/catch for each route correct at the start

wide palm
#

Just the one.

#

If you have external things that can throw their own errors handle those in your service, not in the route handler.

ripe aurora
#

No like one try catch at start of the chain for each service or middleware

midnight lotus
#

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));