Stack Overflow Asked by Kaizen Tamashi on November 17, 2021
I’m trying to simplify handling of HTTP Status Codes for a REST API.
I would like to know which of the following intervals of status codes have the possibility to occur in REST API?
-Informational responses (100–199)
-Successful responses (200–299)
-Redirects (300–399)
-Client errors (400–499)
-Server errors (500–599)
It is currently handling only 3 intervals of HTTP Status Codes in the following way.
Is it necessary to handle the remaining 2 intervals namely Informational responses (100–199)
and Redirects (300–399)
?
I’m really confused and trying to find the correct solution to handle http status codes on both server side and client side.
SERVER SIDE
switch(Math.floor(statusCode/100)){
case 2:
err.status = 'OK'
break;
case 4:
err.status = 'CLIENT ERROR';
break;
case 5:
err.status = 'SERVER ERROR';
}
res.status(statusCode).json({
status: status,
message: message
data: data
});
CLIENT SIDE
const res = axios.get('https://www.example.com/things);
if(res.data.status == 'OK'){
showThings(res.data.data);
console.log('Request successfully processed.');
} else if(res.data.status == 'CLIENT ERROR') {
console.log('Request failed due to client error');
} else if(res.data.status == 'SERVER ERROR') {
console.log('Request failed due to server error.');
}
IANA is the entity that takes care of administrating all of the standardized HTTP operations, link-relations and status-codes.
As such currently IANA has the following status codes registered:
Any other status code you might receive are non-standardized customizations that might not be understood by generic HTTP clients.
Answered by Roman Vottner on November 17, 2021
An API can return any status code it wishes to. Whether you have to handle it or not is a matter of the contract between your system and the API: ideally, a well-documented API will list all possible status codes it can return, eliminating the guesswork.
In most real-world cases, though, you can assume anything in the 200-299 range "succeeded", and anything else did not. Your distinction between 4xx and 5xx is correct. 3xx's are a little weird, as a 301/302 means you might just need to follow the redirect, and sometimes a 304 Not Modified will still mean the operation succeeded, but it depends on the API's implementation. 1xx's are not expected in a REST API.
Lastly, remember that while each status code has a meaning, they're only as meaningful as the API makes them. I have seen many production APIs that return 200s even for error responses, instead pushing the error status down into the body payload. Take care when generalizing your error handling to still allow the callers to access the original response for edge cases like these.
Answered by Robert Nubel on November 17, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP