我无法理解为什么在 .catch
中使用 throw
会导致“未处理的 promise 拒绝”
。如果我只是 console.log
错误,一切都会正常工作。
"throw ... raises an exception in the current code block and causes it to exit, or to flow to next catch statement if raised in a try block.
console.error just prints out a red message to the browser developer tools javascript console and does not cause any changes of the execution flow."
( https://stackoverflow.com/a/25377160/7825826 )
看来 throw 是正确的处理方法?但为什么我会收到错误消息?
例如(如果我没有在 1330 上运行任何数据库):
mongoose.connect('mongodb://localhost:1330/db')
.catch((error) => {
throw error;
});
给我一条关于“未处理的 promise 拒绝”的错误消息,但如果我console.log(error)
,那就没问题了。
最佳答案
当您在 catch
回调中重新引发错误时,结果 promise 将被拒绝。如果该拒绝未在任何地方得到处理(由链下的另一个 .catch
处理),您将收到“未处理的拒绝”消息。
这相当于同步
try {
connectToNotExistingDatabase(); // throws exception
} catch(error) {
throw error;
}
执行时仍会向调用者抛出异常。相反,如果您没有重新抛出
它(但console.log
ged它),它只会返回undefined
。
关于node.js - throw 和 console.log 与 catch 中的 Promise 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251206/