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

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

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 Denunciar

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 Denunciar

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 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