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

281
Visualizações
How to throw an exception with a status code?

How can throw an error with options or a status code and then catch them?

From the syntax here, it seems we can through the error with additional info:

new Error(message, options)

So, can we throw like this below?

throw new Error('New error message', { statusCode: 404 })

Then, how can we catch that statusCode?

try {
 //...
} catch (e) {
  console.log(e.statusCode) // not working off course!
}

Any ideas?


Options are not supported yet.

Re-throw the error works:

try {
  const found = ...

  // Throw a 404 error if the page is not found.
  if (found === undefined) {
    throw new Error('Page not found')
  }

} catch (error) {
  // Re-throw the error with a status code.
  error.statusCode = 404
  throw error
}

but it is not an elegant solution.

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

0

You can use err.code

const error = new Error("message")
error.code = "YOUR_STATUS_CODE"
throw error;
about 4 years ago · Juan Pablo Isaza Relatório

0

as described here you have to create a custom exception for this:

function CustomException(message) {
  const error = new Error(message);

  error.code = "THIS_IS_A_CUSTOM_ERROR_CODE";
  return error;
}

CustomException.prototype = Object.create(Error.prototype);

then you can throw your custom exception:

throw new CustomException('Exception message');
about 4 years ago · Juan Pablo Isaza Relatório

0

based on response

const error = new Error(response?.error || 'error message here'); // error message
error.code = response?.code || 404; // you can custom insert your error code
error.name = "NOT FOUND"; // you can custom insert your error name
throw error;
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