Last active
April 4, 2017 21:30
-
-
Save aortbals/ea927d8698afadb85da0a7e1dd1218a0 to your computer and use it in GitHub Desktop.
Check the status of a fetch response
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
/** | |
* Check the status of a fetch response. | |
*/ | |
export default function checkStatus(response) { | |
if (response.ok) { | |
return response; | |
} | |
const error = new Error(response.statusText); | |
error.response = response; | |
// If the error response is JSON, attempt to parse it. | |
const contentType = response.headers.get('content-type'); | |
if (contentType && contentType.match('application/json')) { | |
return response.json().then((json) => { | |
error.data = json; | |
throw error; | |
}).catch(() => { | |
throw error; | |
}); | |
} | |
throw error; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment