javascript - Node.js / MongoDB:无法从该回调之外的 Cursor.map 回调中捕获错误
问题描述
MongoDB 3.6.3
节点 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
块中使用异步函数,异步函数会超出try..catch
块的范围,因此,在异步函数回调中返回错误总是一个好习惯,可以通过简单的if..else
检查来处理。
示例 1:在 async-await 中抛出错误,其中没有异步进程正在运行。
(async () => {
const someAsync = async () => {
throw new Error('error here');
};
try {
await someAsync();
} catch (e) {
console.log('error cached as expected!');
}
console.log('execution continues');
})();
示例 2:在异步进程正在运行的 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 - Nodemailer 在实时服务器上失败
- swift - 将 UIPanGesture 与 SpriteKit 一起使用
- sprite-kit - CGMutablePathRef 或 SKShapeNode 不在正确位置
- javascript - 检查 'PodCastScreen' React Native 的渲染方法
- javascript - JS注册表未将所有信息提交到MYSQL数据库
- python - 'float' 类型的非 int
- heroku - Heroku Spring Redis - SessionDestroyedEvent
- python - 解析从 Internet 派生的 XML 文件
- sql - 查询重复记录
- dns - 要启用 DNSSEC,是否需要将域名服务器设置为域注册商?