node.js - throw 和 console.log 与 catch 中的 Promise 的区别

标签 node.js ecmascript-6

我无法理解为什么在 .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.logged它),它只会返回undefined

关于node.js - throw 和 console.log 与 catch 中的 Promise 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251206/

相关文章:

javascript - 更改对象数据

javascript - 使用 Node 和 Express 将查询字符串作为实际字符串传递给请求

javascript - 如何在aws lambda中调用javascript类处理函数

javascript - react 输入元素中的 "ReferenceError: getInput is not defined"

javascript - 如何将模型对象数组转换为以模型 ID 作为键的对象?

node.js - @typescript-eslint/eslint-plugin@2.3.2 : The engine "node" is incompatible with this module

php - 从nodejs服务器发送文件到slimframework

javascript - 填充 React 下拉列表时出现错误 #31

javascript - 无法针对对象数组设置状态 : React JS

javascript - 创建一个从 ES6 Map 扩展的类