【问题标题】:How to properly catch exception from MongoDB?如何从 MongoDB 中正确捕获异常?
【发布时间】:2020-01-29 18:05:26
【问题描述】:

问题

如果在 MongoClients connect 函数内部,我的 try 不会出现 catch 错误


环境

  • Linux(薄荷、泰莎)
  • Node.js v10.16.0(使用 ES6 和 nodemon
  • MongoClient(来自 mongodb npm 存储库)

示例

如果我试试这个:

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

我得到 clean exit(很好 - 工作)

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...

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

【问题讨论】:

    标签: javascript node.js mongodb nodemon


    【解决方案1】:

    试试这个

    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() 样式代码也会发生同样的事情。

    注意:如果要使用 await,请在函数名称前使用 async 关键字。

    例如:

    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'); }
       });
    

    【讨论】:

    • 不错的收获!我不认为 Mongo 是异步工作的。我完全不理解您使用await 的解决方案(比如成功块在哪里?)。但是thencatch 运行良好。
    • 你说的是哪个成功块?您可以在此处找到有关使用 async-await 语法的 try catch 的更多详细信息:stackoverflow.com/questions/44663864/…
    • 我明白,但是在您的eg: 块中,您已经定义了async test() 函数,但是解析的变量去哪里了?您只捕获了err,但没有更多的db 变量。如果我尝试使用我的代码(回调函数在哪里设置 errdb 并将 await 放在它之前(+ 在异步函数中调用) - 它没有捕获任何东西。
    猜你喜欢
    • 2016-08-20
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多