Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!