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

148
Vistas
switch for http status code

How can I do a switch statement to return error message based on the http status code, I did this:

switch(true){
    case err.status.test(/^4/): // 4xx
       res.fail(err.status, err);
       break;
    case err.status.test(/^5/): // 5xx
       res.error(err.status, err.message, {data: err});
       break;

Is my regex doing it right?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

test() is a RegExp method, so it should be:

case /^4/.test(err.status):

I personally think switch(true) { ... } is a confusing coding style. I would write it as:

switch(Math.floor(err.status/100)) {
    case 4:
       res.fail(err.status, err);
       break;
    case 5:
       res.error(err.status, err.message, {data: err});
       break;
}
about 4 years ago · Santiago Trujillo Denunciar

0

one can also try making an error object, where keys will the status code and value will be the respective error/success message. For example

errorObj = {1 : 'Informational responses', 2: 'Success', ...}
console.log(errorObj[Math.floor(err.status/100)])

It serves the purpose in less number of lines most of the time.

about 4 years ago · Santiago Trujillo 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