简体   繁体   中英

Unhandled promise rejection when trying to throw error in async function

I am implementing a piece of code which goes through project's build and checks if there are multiple pages with featured: true . If that is a case, I want to throw an error, so that qa job in a pipeline would fail. Everything would work fine but I am getting:

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()

this is my code:

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

How can I throw an error in async function?

You can error can be handled with a catch block, like this:-

/* 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM