使用Node v8.1.4运行以下代码:
testPromise((err) => {
if (err) throw err;
});
function testPromise(callback) {
Promise.reject(new Error('error!'))
.catch((err) => {
console.log('caught');
callback(err);
});
}
返回以下内容:
caught
(node:72361) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): Error: test
(node:72361) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我原以为会抛出uncaughtException
?
如何将此变为未捕获的异常?
答案 0 :(得分:2)
你实际上是在catch回调中抛出。这被抓住并变成另一个被拒绝的承诺。所以你没有得到uncaughtException
Promise.reject("err")
.catch(err => {
throw("whoops") //<-- this is caught
})
.catch(err => console.log(err)) // and delivered here -- prints "whoops"
要注意的一件事是抛出的异步函数。例如,这是一个未被捕获的例外:
Promise.reject("err")
.catch(err => {
setTimeout(() => {
throw("whoops") // <-- really throws this tim
}, 500)
})
.catch(err => console.log(err)) //<-- never gets caught.