Abazhenov / express-async-handler

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

Throw await syntax in Nodejs async express handler is not working #55

Open samislam opened 2 years ago

samislam commented 2 years ago
const express = require("express");
const expressAsyncHandler = require("express-async-handler");

const app = express();

const f = async () => {
  return false;
};

app.get(
  "/",
  expressAsyncHandler(async () => {
    throw await f();
  }),
  () => {
    console.log("the bug!");
  }
);

app.use((err, req, res, next) => {
  console.log("caught!", err);
});

app.listen(4000, () => console.log("listening on port 4000..."));

Expected output on the console:

"caught!".

output:

the bug!.

question: Why? Is it a bug in async-express-handler package or is it a normal JavaScript behaviour? what if I want to throw await something inside? how ?

MiccWan commented 2 years ago

@samislam

I think this is an intended design by express.

Although, express.js said that "If you pass anything to the next() function (except the string 'route'), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.", they actually ignoring any falsy values passed to next().

In your case, f() is returning false and is ignored by express. Instead of false, you may throw an error e.g. new Error('some error message...') or any value that is not falsy.

I'm not the maintainer of express-async-handler by the way and I hope you find this information helpful.

bergus commented 2 years ago

Cross-posted on StackOverflow: Throw await syntax in Nodejs async express handler is not working (with pretty much the same conclusion as @MiccWan).

You may close this issue I think.

samislam commented 2 years ago

Cross-posted on StackOverflow: Throw await syntax in Nodejs async express handler is not working (with pretty much the same conclusion as @MiccWan)

Yes, it's actually me