【发布时间】:2018-12-25 17:28:36
【问题描述】:
我在 express 中有一个 async 中间件,因为我想在其中使用 await 来清理我的代码。
const express = require('express');
const app = express();
app.use(async(req, res, next) => {
await authenticate(req);
next();
});
app.get('/route', async(req, res) => {
const result = await request('http://example.com');
res.end(result);
});
app.use((err, req, res, next) => {
console.error(err);
res
.status(500)
.end('error');
})
app.listen(8080);
问题是,当它拒绝时,它不会转到我的错误中间件,但如果我删除中间件中的 async 关键字和 throw ,它会这样做。
app.get('/route', (req, res, next) => {
throw new Error('Error');
res.end(result);
});
所以我得到UnhandledPromiseRejectionWarning,而不是进入我的错误处理中间件,我怎样才能让错误冒出来,并快速处理它?
【问题讨论】:
-
这是我在谷歌搜索时发现的一篇好文章:strongloop.com/strongblog/…
标签: javascript node.js express es6-promise