Express 4的asynchronous包装函数不会捕获错误

我试着从strongloop这个技巧https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/有一个asynchronous路由包装function,但错误的function从来没有被调用。 我也尝试把错误函数放在authRouter文件中。

在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; 

并在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 }); }); 

您需要在error handling程序中有4个参数才能使快速识别为一个:

(来自http://expressjs.com/en/guide/error-handling.html ):“ 定义error handling中间件函数的方式与其他中间件函数相同,除了error handling函数有四个参数而不是三个:( (err, req, res, next)

这是最后一个error handling程序,我不想调用next()

这并不重要,即使你不使用它,你仍然需要声明它。