Created
February 23, 2019 20:56
-
-
Save luismartinezs/5abab7ece43e3b6c17f7b36892739e92 to your computer and use it in GitHub Desktop.
Check status code of API response #js #http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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