davidbanham / express-async-errors

async/await support for ExpressJS
Other
900 stars 43 forks source link

What is the purpose of calling next after handling the error? #34

Open ajsaraujo opened 3 years ago

ajsaraujo commented 3 years ago

README.md proposes this handling function:

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

  next(err);
});

But what is the purpose of calling next(err) after the error is handled?

I based my handling function on that and I was having problems with it. Express was throwing the error again when I called next(error). After I removed it, the code worked just fine. I believe this might be the cause for the problem some people are reporting in #33.

davidbanham commented 3 years ago

It's to allow you to have additional middleware running outside this one that do extra things with your errors. For example you might have something that logs error information to a third party tracking/tracing service.

ajsaraujo commented 3 years ago

Oh, I get it. It makes more sense now.

Anyways, I think it would be nice if the docs explained that. I mean, picture the following situation:

Someone just downloaded express-async-errors and is following along with the docs to use it in their app. He followed it step by step, but his errors are still getting thrown and he can't figure out why. It can be a bit frustrating, this person may even give up on using the library, thinking that it doesn't work as expected.

So I guess it would be more clear if the docs also proposed doing the other way around, giving the same explanation you just gave me. If you're ok with it I can come up with a PR to tackle this matter.