Created
November 24, 2023 13:38
-
-
Save lejonmanen/db4b55542b8863c4c435f66881ff7534 to your computer and use it in GitHub Desktop.
Using fetch with try+catch
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
// 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