davidbanham / express-async-errors

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

Unexpected behavior handling async route handlers and Express Error middleware #38

Closed bunchito closed 2 years ago

bunchito commented 2 years ago

I'm trying this package but I cannot make it work with the "Express Error Middleware".

src/routes/users.js

// ... code

router.get('/', async function (req, res) {
  throw new Error('Broken');
});

// ... code

src/index.js

// ... code

require('express-async-errors');
const users = require('./routes/users');

app.use('/users', users);

// Last middleware
app.use(function(err, req, res, next){
  console.error( err.stack);
  res.status(500).send('Something broke!');
  next(err);
});

// ... code

When I make a GET request to http://127.0.0.1:3333/users I see:

In the console

  throw new Error('BROKEN')
        ^
Error: BROKEN

The application crushes and process exits. There is not hitting the express error middleware and there is no 500 response.

If I create my own async handler and wrap the user route, the express error middleware works: src/routes/users.js

// ... code

function asyncError(handler) {
  return async (req, res, next) => {
    try {
      await handler(req, res);
    } catch (err) {
        next(err);
    }
  }
}

router.get('/', asyncError(async function (req, res) {
  throw new Error('Broken');
}));

// ... code

When I make a GET request to http://127.0.0.1:3333/users I see:

In the console

Error: BROKEN

And I receive a 500 response with the text Something broke!

How can I achieve this behavior with this library? Thanks!

kronicker commented 2 years ago

Whats the order of your imports/requires?

bunchito commented 2 years ago

Thanks, @kronicker Your comment helped me to resolve the issue. It was the last (bottom). I moved it first (top) and now everything works as expected.

kronicker commented 2 years ago

No problem. Since it's patching express it should be required right after express.