Skip to content

Instantly share code, notes, and snippets.

@aortbals
Last active April 4, 2017 21:30
Show Gist options
  • Save aortbals/ea927d8698afadb85da0a7e1dd1218a0 to your computer and use it in GitHub Desktop.
Save aortbals/ea927d8698afadb85da0a7e1dd1218a0 to your computer and use it in GitHub Desktop.
Check the status of a fetch response
/**
* 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