我在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
,而不是进入我的错误处理中间件,我如何让错误冒泡,并表示处理它?