Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Alvin Avatar asked Jul 29 '26 02:07

Alvin


1 Answers

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;
}
like image 160
Barmar Avatar answered Jul 30 '26 14:07

Barmar