Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created November 24, 2023 13:38
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 lejonmanen/db4b55542b8863c4c435f66881ff7534 to your computer and use it in GitHub Desktop.
Save lejonmanen/db4b55542b8863c4c435f66881ff7534 to your computer and use it in GitHub Desktop.
Using fetch with try+catch
// Simple request
async function sendRequest(url) {
try {
const response = await fetch(url)
if( response.status !== 200 ) {
console.log('Request wasn't successful. Code: ' + response.status)
return null
}
const data = await response.json()
return data // success
}
catch {
// This only executes if an error occurred
// We need to determine at what point the error happened
if( !response ) {
// 1. fetch failed totally
}
else if( !data ) {
// 2. fetch was successful, but we didn't get a JSON response
}
return null
}
}
/*
Possible causes for #1:
+ the user has no internet
+ the server is offline
+ you used the wrong URL (wrong domain)
Possible causes for #2:
+ you used the wrong URL (correct domain but wrong path)
+ the server sent back HTML (because you used the wrong method or URL)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment