【问题标题】:Unhandled promise rejection when trying to throw error in async function尝试在异步函数中抛出错误时未处理的承诺拒绝
【发布时间】:2022-01-12 15:49:36
【问题描述】:

我正在实现一段代码,该代码通过项目的构建并检查是否有多个带有featured: true 的页面。如果是这种情况,我想抛出一个错误,这样管道中的qa 作业就会失败。一切都会很好,但我得到了:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

这是我的代码:

/* eslint-disable no-restricted-syntax */
const fs = require('fs');
const findInDir = require('./utils/findInDir');

(async () => {
  const dir = './public/page-data/blog';
  const fileRegex = /.*/;
  const allFiles = findInDir(dir, fileRegex);
  let result = 0;

  for (const file of allFiles) {
    try {
      // eslint-disable-next-line no-await-in-loop
      const data = await fs.promises.readFile(file);
      const obj = JSON.parse(data);

      if (obj.result.pageContext.featured === true) {
        result += 1;
      }
    } catch (err) {
      // noop
    }
  }

  if (result > 1) {
    throw new Error('There are multiple featured blog posts, please fix.');
  }
})();

如何在异步函数中抛出错误?

【问题讨论】:

  • 正在在异步函数中抛出错误,这正是您看到该消息的原因。该消息说您在异步函数中抛出了一个错误,并没有在任何地方处理。
  • 你的外部 async 包装器根本没有错误处理,所以如果你让一个被拒绝的承诺到达那里,那么你会得到UnhandlePromiseRejectionWarning。要么在所有错误退出您的 async 函数包装器之前捕获所有错误,要么在该包装器上进行错误处理。
  • 另外findInDir 可能会抛出错误
  • 这样管道中的qa 作业会失败”是什么意思?那份工作如何调用你的脚本?你需要做什么才能让它失败?

标签: javascript node.js asynchronous


【解决方案1】:

您可以使用 catch 块来处理错误,如下所示:-

/* eslint-disable no-restricted-syntax */
const fs = require('fs');
const findInDir = require('./utils/findInDir');

(async () => {
  const dir = './public/page-data/blog';
  const fileRegex = /.*/;
  const allFiles = findInDir(dir, fileRegex);
  let result = 0;

  for (const file of allFiles) {
    try {
      // eslint-disable-next-line no-await-in-loop
      const data = await fs.promises.readFile(file);
      const obj = JSON.parse(data);

      if (obj.result.pageContext.featured === true) {
        result += 1;
      }
    } catch (err) {
      // noop
    }
  }

  if (result > 1) {
    throw new Error('There are multiple featured blog posts, please fix.');
  }
})().catch((e) => {
    console.log(e);
});

【讨论】:

  • 可以说,在这种情况下,你为什么要先扔而不是把console.log放到if (result > 1)...?
  • 同意!我的目的只是展示如何处理此类函数中的错误。
  • @deceze 函数中可能还有其他点会引发异常
猜你喜欢
  • 1970-01-01
  • 2020-03-22
  • 2019-07-03
  • 2020-03-22
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2019-02-21
  • 2019-08-30
相关资源
最近更新 更多