Abazhenov / express-async-handler

Async Error Handling Middleware for Express
572 stars 39 forks source link

Description of this project in README.md is unclear #47

Open rjmunro opened 3 years ago

rjmunro commented 3 years ago

I'm reviewing code that uses this project, and it's unclear from the README what it is needed for.

It doesn't seem to be middleware as such, it seems something you wrap around your functions to turn async requests into ones that call the next() method. I thought that express could already do this built in, so why is this needed? Does express not try ... catch async methods or something? Is this not needed any more - is it legacy from before express did async methods (and / or promises) natively?

It would be good if the README had a bit more explanation of why you need this, compared to normal:

Why do you need:

app.get('/foo', asyncHandler(async (req, res) => {
  ...
}));

When you can just do:

app.get('/foo', async (req, res) => {
  ...
});
willwillems commented 2 years ago

Does express not try ... catch async methods or something?

☝️

ralph993 commented 2 years ago

'For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next()' So basically this call next in every route so express can throw the errors, otherwise the server stays hanging

You can try throwing an error inside an asynchronous functions without wrapping your function inside asyncHandler() and see what happens.

abierbaum commented 2 years ago

@rjmunro This post provides a great description of why I think this project is useful. https://zellwk.com/blog/async-await-express/

0x80 commented 2 years ago

Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error. For example:

app.get('/user/:id', async function (req, res, next) {
  var user = await getUserById(req.params.id)
  res.send(user)
})

☝️ Doesn't this make the NPM package obsolete now? Quoted from here

--- edit ---

Ah, I see Express 5 is not released as a stable version yet.