我正在使用 Nodejs。
我有一个 promise ,会在几秒钟后请求。 但我的中间件没有捕获错误,但 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..
});
问题是这样的: 假设我有另一个图书馆的登录功能,它给了我一个 promise 。 函数中出现了某些问题,我无法捕获错误中间件中的错误以向用户提供请求失败的响应。
- 我不想在每个中间件中添加 try/catch。 (路由===中间件)
- 我想使用 async/await
- 使用 uncaughtException 对我没有帮助,因为我无法向路由中的用户返回响应。
那我能做什么呢?有什么想法吗?
最佳答案
这应该对你有帮助
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);
})
.catch((err) => {
clientErrorHandler(err);
});
关于javascript - 中间件不会捕获带有等待的 Promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486688/