davidbanham/express-async-errors

What purpose does calling next() serve?

Closed this issue · 1 comments

I'm wondering why we need to call next(err) (as given in the snippet)

app.use((err, req, res, next) => {
  if (err.message === 'access denied') {
    res.status(403);
    res.json({ error: err.message });
  }
 
  next(err);
});

So whenever something is thrown in the previous middleware, it rolls down to the above error handler, I handle the error inside it and that's that. If I have the next() (which I'm not really sure what it does here) I get the error stack trace again in my console which makes me think that node thinks that I forgot to catch it myself.

So, what does next() do here and is it okay to just not have it?

Check out this doc:

http://expressjs.com/en/guide/error-handling.html

Specifically the last heading The Default Error Handler

The tl:dr is that passing the err object to the next handler invokes that default error handler, which prints a stack trace.

There's nothing at all stopping you from leaving out that next call if you don't want that behaviour.

I'm closing this issue with the assumption that this answers your question. If not, let me know.