arisalexis arisalexis - 2 months ago 10
Node.js Question

Async wrap function for express 4 doesn't catch error

I am trying out this trick from strongloop https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/ for having a wrap function for async routes
but the error function is never called. I also tried to put the error function inside the authRouter file.

in authRouter.js:

let wrap = fn => (...args) => fn(...args).catch(args[2]);

router.post('/login', wrap(async (req,res) => {
if (!req.body.email || !req.body.password) throw new Errors.BadRequestError();
}));

export default router;


and in app.js

app.use('/auth', authRouter);

app.use(function(err, req, res) {
console.log('in here');
const status = err.status || 500;
if (status === 500) console.log(err);

res.status(status);
res.send({
message: err.message,
error: err
});
});

Answer

You need to have 4 parameters in the error handler to make express recognise it as one:

(from http://expressjs.com/en/guide/error-handling.html): "Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next)."

this is the last error handler I don't wanna call next()

That doesn't really matter, you still have to declare it even if you don't use it.

Comments