我正在尝试来自 strongloop https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/ 的这个技巧为异步路由提供包装功能 但永远不会调用错误函数。我还尝试将错误函数放在 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
});
});
最佳答案
您需要在错误处理程序中有 4 个参数才能使 express 将其识别为一个:
(来自 http://expressjs.com/en/guide/error-handling.html):“以与其他中间件函数相同的方式定义错误处理中间件函数,除了错误处理函数有四个参数而不是三个:(err, req, res ,下一个)
。“
this is the last error handler I don't wanna call next()
没关系,不用也得申报
关于javascript - express 4 的异步包装函数不会捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752154/