【发布时间】:2018-03-21 19:27:09
【问题描述】:
我有以下简化的中间件功能:
router.put('/', function (req, res, next) {
const data = req.body;
const q = req.parsedFilterParam;
const opts = req.parsedQueryOpts;
ResponseCtrl.update(q, data, opts)
.then(stdPromiseResp(res))
.catch(next);
});
我想为中间件添加一些捕获错误的功能,只是为了节省一些代码,如下所示:
router.put('/', function (req, res, next) {
const data = req.body;
const q = req.parsedFilterParam;
const opts = req.parsedQueryOpts;
return ResponseCtrl.update(q, data, opts)
.then(stdPromiseResp(res));
});
所以我们现在在中间件函数中返回承诺,我们可以放弃 catch 块。
所以在内部,它现在可能看起来像这样:
nextMiddlewareFn(req,res,next);
只是想把它改成:
const v = nextMiddlewareFn(req,res,next);
if(v && typeof v.catch === 'function'){
v.catch(next);
});
有谁知道如何用 Express 做到这一点?
【问题讨论】:
-
我想我们可以切换到 Koa,这可能会解决它。但是简单地使用 async/await 可能不会解决它,或者会吗?
-
做我在问题中寻找的东西并不安全。如果所有中间件都只在 Promise 解析后调用,会更安全。
-
这最终对我有用:medium.com/@the1mills/…