javascript - Node.js/MongoDB : can't catch error from Cursor. 映射回调在此回调之外

标签 javascript node.js mongodb

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 检查来处理。

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

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/

相关文章:

javascript - 如何使用 w3c 选项卡样式链接到特定选项卡

javascript - Jquery 对选择器的响应差异 $ ('#tag_field_2' ) 和 $ ('input[style]' )[0]

javascript - 是否可以清除 NGZone 中设置的所有间隔?

mongodb - 使用Go驱动程序在MongoDB中运行命令

javascript - jquery .hasClass 不工作应该

javascript - Express - 循环查询时 Promise 挂起

javascript - 将 url 传递给模块

javascript - 在 Javascript 中将字符串转换为数组的数组

javascript - Stripe 和 MogoDB 集成的 GraphQL 突变过早返回 null

javascript - 如何使用 Mongoose 进行查询,然后使用该文档执行其他操作?