Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda