Skip to content

Instantly share code, notes, and snippets.

@uwuru
Created July 20, 2019 20:30
Show Gist options
  • Save uwuru/840f43681c3df82e64e9a4c6d7c57e5e to your computer and use it in GitHub Desktop.
Save uwuru/840f43681c3df82e64e9a4c6d7c57e5e to your computer and use it in GitHub Desktop.
Javascript fetch with better error handling example
return fetch(url)
.then((response) => {
if (response.ok) {
return response.json()
}
throw response
})
.catch((error) => {
if (error instanceof Error) {
return { error }
}
return error.json().then((responseJson) => {
return {
error: new Error(
`HTTP ${error.status} ${error.statusText}: ${responseJson.msg}`
)
}
})
})
@uwuru
Copy link
Author

uwuru commented Jul 20, 2019

Firstly, fetch doesn't throw errors normally for HTTP 400 errors etc.

Secondly, response JSON has a msg field with useful information for the error. Let's use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment