Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
UnhandledPromiseRejectionWarning even though wrapped in try/catch()

I'm getting the following error message when trying to run storeDirectory().

Why doesn't my catch() statement not catch the error that is thrown inside addFile()?

My understanding is that errors bubble up to any "outer" catch statement but that doesn't seem to be the case in my code.

(node:21204) UnhandledPromiseRejectionWarning: Error: HTTP error 500
    at addFile (/Users/joe/dev/node/db/dbFunctions.js:28:11)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:21204) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
//dbFunctions.js
...
const addFile = async (name, type, href) => {
  const response = await fetch("http://localhost:3002/files", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name,
      type,
      href
    }),
  });
  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
  }
  return response.json();
};
//app.js
const { addFile } = require("./db/dbFunctions");
...
const storeDirectory = async () => {
  try {
    //create array of files
    const response = await getDirectory();
    const arr = response.directory.items;

    //loop through array and add each item to database
    arr.map((item) => {
      //add item to DB
      addFile(
        item.name,
        item.type,
        item.href
      );
    });
  } catch (error) {
    console.log(error);
  }
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

try will only catch asynchronous errors if the Promise is awaited. Change

arr.map((item) => {
  //add item to DB
  addFile(
    item.name,
    item.type,
    item.href
  );
});

to

await Promise.all(arr.map((item) => 
  //add item to DB
  addFile(
    item.name,
    item.type,
    item.href
  );
));

making sure to return the Promise from the .map.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda