相关疑难解决方法(0)

处理Express异步中间件中的错误

我有一个asyncExpress中间件,因为我想在其中使用中间件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);
Run Code Online (Sandbox Code Playgroud)

问题是当它拒绝时,它不会进入我的错误中间件,但是如果我删除了async关键字,并且throw在中间件内部,它就会去。

app.get('/route', (req, res, next) => {
    throw new Error('Error');
    res.end(result);
});
Run Code Online (Sandbox Code Playgroud)

所以我得到的UnhandledPromiseRejectionWarning不是输入我的错误处理中间件,而是如何让错误冒泡并表达处理它?

javascript node.js express es6-promise

5
推荐指数
5
解决办法
4598
查看次数

标签 统计

es6-promise ×1

express ×1

javascript ×1

node.js ×1