Last active
August 16, 2018 15:29
-
-
Save ddelrio1986/fe8a58f30eca9d9bd2a1405e7a83dc07 to your computer and use it in GitHub Desktop.
Handle fetch errors
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
export function handleJSONResponse (response) { | |
return response.json() | |
.then(json => { | |
if (response.ok) return json | |
return Promise.reject({...json, responseObj: response}) | |
}) | |
} | |
export function handleTextResponse (response) { | |
return response.text() | |
.then(text => { | |
if (response.ok) return text | |
return Promise.reject({responseObj: response, text}) | |
}) | |
} | |
export default function handleResponse (response) { | |
let contentType = response.headers.get('content-type') | |
if (contentType.includes('application/json')) return handleJSONResponse(response) | |
return handleTextResponse(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
import handleResponse from './handleResponse' | |
fetch('https://api.github.com/users/chrissycoyier/repos') // this will 404 on purpose and get a json response from github | |
.then(handleResponse) | |
.then(response => console.log(response)) | |
.catch(error => console.log(error)) // error here will contain information about the response and json response from github |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment