LongStreak
LongStreak

Reputation: 111

Do I *need* to use next(err) with Express.js?

Basically, the question is do I need to use next(err) when encountering any errors? The nodejs error documentation says it is fine to use a standard sort of if(err) else... for asynchronous callbacks and EventEmitters, as long as the error isnt handled with a try-catch block for non async-await functions, as it will cause crashing. If I do need to use them, what is to prevent the next() function being called multiple times in the same handler for different asynchronous operations? Wouldnt using the default error handler cause headers to be sent multiple times and cause an error of its own when using event emitters ?

Apologies if the question has been asked, its just I cannot find a specific answer to why usage of express.js error handling is preferred.

Upvotes: 4

Views: 1402

Answers (1)

jeeves
jeeves

Reputation: 2031

If you are asking if you need to use an explicit next(err) in a handler, e.g.

app.get('/someurl', (req, res, next) => {
   //do something - whoops had an error
   next(err);
})

No, the above is not required in a handler. The only time you would need to explicitly wrap or pass on the error is if you have, for example, used a try/catch and are not handling the error condition itself in the handler, i.e. not returning a response in the handler (Not sure why you would want to do that).

What will happen above when an error occurs in the handler, express will continue on through the middlewares until it finds a handler that will deal with your error. If there are none, it will exit.

So to use a global error handler, you could write your app like the following and not worry about next(err) in each handler function.

app.get('/route/one', async (req, res) => {
   // do something that could throw an error
   const result = await aFunctionThatCouldThrowAnError();
   // No error handling in this function
   res.json({ result });
});

app.get('/route/two', (req, res) => {
   res.json({ hello: 'world-two' });
});

// A Global Error handler
app.use((err, req, res, next) => {
    //handle all errors here
    if(err) {
       res.status(500).send('some error message')
    }
    res.status(404).send('not found');
});

Note that the order of middlewares is important, so the global error handler should be applied last.

Upvotes: 4

Related Questions