Created
July 20, 2019 20:30
-
-
Save uwuru/840f43681c3df82e64e9a4c6d7c57e5e to your computer and use it in GitHub Desktop.
Javascript fetch with better error handling example
This file contains hidden or 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
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}` | |
) | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.