arisalexis arisalexis - 10 months ago 46
Node.js Question

Async wrap function for express 4 doesn't catch error

I am trying out this trick from strongloop 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]);'/login', wrap(async (req,res) => {
if (! || !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);

message: err.message,
error: err

Answer Source

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

(from "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.