【发布时间】:2018-05-09 06:15:17
【问题描述】:
我正在使用 Nodejs。
我有一个承诺,几秒钟后请求。 但是我的中间件没有捕捉到错误,但是 uncaughtException 捕捉到了。
router.all('/incaseoferror', async(req, res, next) => {
const promise = await new Promise(function (resolve, reject) {
setTimeout(function () {
reject(new Error('this is a test err, the error-middleware NOT catch and it NOT OKAY'));
}, 3000);
});
// throw new Error('test error - the error-middleware catch it and that okay');
});
function clientErrorHandler(err, req, res, next) {
console.log('in clientErrorHandler', err);
//but not catch the promise error!
});
process.on('uncaughtException', function (error) {
// the error is catch here..
});
问题出在: 假设我有另一个库的登录功能,它给了我一个承诺。 函数中的某些内容失败了,我无法在我的错误中间件中捕获错误以向用户响应请求失败。
- 我不想在每个中间件中添加 try/catch。 (路由===中间件)
- 我想使用异步/等待
- 使用 uncaughtException 对我没有帮助,因为我无法在路由中向用户返回响应。
那我该怎么办?有什么想法吗?
【问题讨论】:
-
也许是时候从 Express 切换到 Koa...
标签: javascript node.js express asynchronous error-handling