mongodb 3.6.3
Node 8.10.0
我无意中发现了这个,经过一段时间研究问题仍然无法弄清楚。我的代码具有应该捕获所有错误的全局错误处理程序,但是它跳过了源自 find().map
回调的错误,并且进程以标准错误日志退出到控制台。
这是我想出的测试代码
(async () => {
const {MongoClient} = require('mongodb');
const uri = 'your uri';
const connection = MongoClient.connect(uri, {useNewUrlParser: true});
connection.catch((e) => {
console.log('inside connection.catch');
console.log(e);
});
const collection = (await connection).db().collection('collection');
const findPromise = collection.find({}).limit(0).skip(0);
const functionWithError = (item) => {
throw new Error('functionWithError');
};
// This fails to catch error and exits process
// try {
// const items = await findPromise.map(functionWithError).toArray().catch((e) => console.log('Promise catch 1'));
// console.log(items);
// } catch (e) {
// console.log('map error 1');
// console.log(e);
// }
// This (obviously) works and 'inside map error' is written to console
try {
const items = await findPromise.map(() => {
try {
functionWithError();
} catch (e) {
console.log('inside map error'); // this will be outputted
}
}).toArray().catch((e) => console.log('Promise catch 2'));
console.log(items);
} catch (e) {
console.log('map error 2');
console.log(e);
}
})();
我没有在代码中看到任何问题,并且希望将 'Promise catch 1'
或 'map error 1'
记录到控制台。所以有什么问题?提前致谢。
最佳答案
关于异步函数的作用域。如果您尝试在 try..catch
block 中使用异步函数,异步函数会超出 try..catch
block 的范围,因此,最好的做法是在异步函数回调中返回错误,可以通过简单的 if..else
检查来处理。
示例 1:在异步等待中抛出错误,其中没有运行异步进程。
(async () => {
const someAsync = async () => {
throw new Error('error here');
};
try {
await someAsync();
} catch (e) {
console.log('error cached as expected!');
}
console.log('execution continues');
})();
Example2:在async-await中抛出错误,异步进程正在运行。
(async () => {
const someAsync = async () => {
let timeInMS = 0; // 0 milliseconds
let timer = setTimeout(function() {
clearTimeout(timer);
throw new Error('error here');
}, timeInMS);
};
try {
await someAsync();
} catch (e) {
console.log('error cached as expected!');
}
console.log('execution continues');
})();
关于javascript - Node.js/MongoDB : can't catch error from Cursor. 映射回调在此回调之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56168533/