问题如果它在 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...所以这意味着它没有捕捉到我的异常。
1 回答
![?](http://img1.sycdn.imooc.com/545847f50001126402200220-100-100.jpg)
www说
TA贡献1775条经验 获得超8个赞
尝试这个
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'); }
});
添加回答
举报
0/150
提交
取消