Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!