Node.js:如何从MongoDB中正确捕获异常?
如果我的try
在MongoClients catch
函数内部,则不会出现connect
错误>
环境
Linux(薄荷,泰莎)
实施例
如果我尝试这样做:
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的connect函数中尝试:
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...
所以这意味着它没有捕获我的异常。
问题,如果它在MongoClients连接功能内部,我的尝试不会捕获错误环境Linux(Mint,Tessa)Node.js v10.16.0(将ES6与nodemon结合使用)MongoClient(来自mongodb npm ...
回答如下:try {
let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
console.log(`Catched: ${err}`);
}