猿问

如何从 MongoDB 正确捕获异常?

问题

如果它在 MongoClients函数内,我try不会catch出错connect


环境

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

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


宝慕林4294392
浏览 316回答 1
1回答

www说

尝试这个try {   let db = await MongoClient.connect(config.url, config.options);} catch (err) {   console.log(`Catched: ${err}`);}async-await/sequential如果您想让 try catch 工作,请尝试以风格编写代码。在这里你可以看到你err在回调中得到第一个参数,为什么它会去 catch 块?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'); }   });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答