javascript - 如何正确捕获 MongoDB 的异常?

标签 javascript node.js mongodb nodemon

问题

如果它位于 MongoClients connect 函数内部,我的 try 不会catch 错误

<小时/>

环境

  • Linux(Mint、Tessa)
  • Node.js v10.16.0(使用 ES6 和 nodemon)
  • MongoClient(来自 mongodb npm 存储库)
<小时/>

示例

如果我尝试这个:

try {
    throw new Error('This is error');
} catch(e) {
    console.log(`Catched: ${e}`);
}

干净退出(很好 - 工作正常)

Catched: Error: This is error
[nodemon] clean exit - waiting for changes before restart

但这不起作用

如果我在 MongoDB 连接函数中尝试:

try {
   MongoClient.connect(config.url, config.options, (err, db) => {
      if (err) { throw new Error('This is error'); }
   });
} catch (err) {
   console.log(`Catched: ${e}`);
}

应用程序崩溃

Error: This is error
[nodemon] app crashed - waiting for file changes before starting...

所以这意味着它没有捕获我的异常。

最佳答案

试试这个

try {
   let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
   console.log(`Catched: ${err}`);
}

如果您希望 try catch 工作,请尝试以 async-await/sequential 风格编写代码。

在这里您可以看到您在回调中将 err 作为第一个参数,为什么它会转到 catch block ? func1().then().catch() 样式代码也会发生同样的情况。

Note: use async keyword in front of your function name if you want to use await.

例如:

async function test() {
   try {
   let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
   console.log(`Catched: ${err}`);
} 
}

MongoClient.connect(config.url, config.options, (err, db) => {
      if (err) { throw new Error('This is error'); }
   });

关于javascript - 如何正确捕获 MongoDB 的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167984/

相关文章:

javascript - jQuery 版本选择完成后运行

http - 返回 JSONP 的 Restful api 的 Node HTTP 请求

node.js - 错误 : Platform can NOT be empty at new Payload in Dialogflow

python - 在 Mongodb 中存储 Numpy 或 Pandas 数据

arrays - MongoDB 获取数组中特定键的计数

javascript - 使用 edge.js 获取对象

javascript - Ajax:从不同域加载XML?

javascript - 扩展 webpack 输出

javascript - Alexa 技能 : Works for the first question but not the second question

mongodb - mongodb中类型不相等的查询