Switch for http status code

How can I make a switch statement to return an 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 correct?

+3


source to share


2 answers


test()

is a method RegExp

, so it should be:

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

      



I personally think this switch(true) { ... }

is a confusing coding style. I would write it like:

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

      

+5


source


you can also try to create an error object where the keys will contain a status code and a value corresponding to the error / success message. for example

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

      



It serves a purpose in fewer lines most of the time.

-1


source







All Articles