Node.js / MongoDB:无法从此回调之外的Cursor.map回调中捕获错误

时间:2019-05-16 12:26:45

标签: javascript node.js mongodb

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'记录到控制台。所以有什么问题?预先感谢。

1 个答案:

答案 0 :(得分:1)

关于异步功能的范围。如果尝试在try..catch块中使用异步函数,则异步函数超出了try..catch块的范围,因此,在异步函数回调中返回错误始终是一种好习惯,这可以通过简单的if..else检查。

Useful link

示例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');
})();

示例2:在异步进程正在运行的异步等待中引发错误。

(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');
})();