【发布时间】:2018-04-06 08:39:51
【问题描述】:
class XYZ {
constructor(app) {
// app is express object
this.app = app;
this.app.route('/api/url')
.get(this.wrap(this.urlhandler.bind(this)));
// to send error as json -> this never gets invoked ??
this.app.use((err, req, res, next) => {
res.status(400).json({error: err});
next(err);
});
}
// wraps each async route function to handle rejection and throw errors
wrap(fn) {
return function (req, res, next) {
Promise.resolve(fn(req, res, next)).catch(function (err) {
console.log('ERROR OCCURED: > > > > > > > ', err.code);
next(err)
});
}
}
}
每个快速 ASYNC 路由都被包装以捕获路由处理函数中的任何拒绝或抛出错误。每当出现此类拒绝或错误时 - wrap 都会被很好地调用,我可以看到“错误发生 > > > ..”的打印。
但是我无法将该错误引导到错误处理程序中间件,我打算在其中发送带有 JSON 错误的 400。
在上述情况下如何解决这个问题??
【问题讨论】:
-
使用你的代码,加上一个总是拒绝的假“urlhandler”,我无法复制你描述的问题,
res.status(400).json({error: err});确实为我调用了
标签: express error-handling promise async-await