Skip to content

Instantly share code, notes, and snippets.

@luismartinezs
Created February 23, 2019 20:56
Show Gist options
  • Save luismartinezs/5abab7ece43e3b6c17f7b36892739e92 to your computer and use it in GitHub Desktop.
Save luismartinezs/5abab7ece43e3b6c17f7b36892739e92 to your computer and use it in GitHub Desktop.
Check status code of API response #js #http
// Status codes reference: https://www.restapitutorial.com/httpstatuscodes.html
// Use something like this when fetching from an external resource, to process the response
const checkStatusCode = response => {
if (response.status >= 200 && response.status < 400) {
return response;
}
if (response.status === 401) {
throw new Error('Unauthorized to use the api!');
}
if (response.status === 403) {
throw new Error('Forbidden access to the requested data!');
}
if (response.status > 500) {
throw new Error('Server error');
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment