问题
如果它位于 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/