Skip to content

Instantly share code, notes, and snippets.

@ddelrio1986
Last active August 16, 2018 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddelrio1986/fe8a58f30eca9d9bd2a1405e7a83dc07 to your computer and use it in GitHub Desktop.
Save ddelrio1986/fe8a58f30eca9d9bd2a1405e7a83dc07 to your computer and use it in GitHub Desktop.
Handle fetch errors
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)
}
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