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

384
Visualizações
What is the difference between throw Error(error) and throw error

What is the difference between:

try {
      const result = await hello();
    } catch (error) {
      throw error;
    }

and

try {
      const result = await hello();
    } catch (error) {
      throw Error(error);
    }

Also

Is the second one necessary? It seems like you are just wrapping an error with an Error Object. Which one is preferred? Please help me understand.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's possible that the value that the Promise rejected with was not an error object, but something else:

(async() => {
  try {
    const result = await Promise.reject(5);
  } catch (error) {
    console.log(error);
    console.log(typeof error);
  }
})();

Doing

throw Error(error);

makes sure that the value being thrown is definitely an Error object, which could be important if the thrown value is examined later and is expected to be such an object. You wouldn't want, for example, for undefined or null to be thrown (strange, I know, but not impossible) and for accessing a property of that to then throw at the point where you're catching for real.

const hello = () => new Promise((resolve, reject) => {
  reject();
});
(async() => {
  try {
    const result = await hello();
  } catch (error) {
    throw error;
  }
})()
  .catch((error) => {
    console.log('The error message was:');
    console.log(error.message);
  });

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