首页 > 解决方案 > 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'记录到控制台。所以有什么问题?提前致谢。

标签: javascriptnode.jsmongodb

解决方案


它关于异步函数的范围。如果你尝试在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');
})();


推荐阅读