这个问题在这里已有答案:
我正在使用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..
});
Here is the problem: 假设我有来自另一个图书馆的登录功能,它给了我一个承诺 . 函数中出现故障,我无法捕获错误 - 中间件中的错误,以便向用户提供请求失败的响应 .
-
我不想在每个中间件中添加try / catch . (路线===中间件)
-
我想使用async / await
-
使用uncaughtException无法帮助我,因为我无法在路由中返回对用户的响应 .
那我该怎么办?有任何想法吗?
1 回答
这应该对你有帮助