Reputation: 8499
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?
Upvotes: 3
Views: 3641
Reputation: 55
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.
Upvotes: 0
Reputation: 780974
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;
}
Upvotes: 6