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

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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