如何正确捕获来自 MongoDB 的异常?
How to properly catch exception from MongoDB?
问题
我的 try
如果它在 MongoClients connect
函数
内部,则不会 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
但这行不通
如果我在 MongoDBs 连接函数中尝试:
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 块? 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'); }
});
问题
我的 try
如果它在 MongoClients connect
函数
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
但这行不通
如果我在 MongoDBs 连接函数中尝试:
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 块? 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'); }
});