Created
September 14, 2023 23:40
-
-
Save asuh/7d3dc277ecdc7d654d8c681bc1b281d3 to your computer and use it in GitHub Desktop.
Defensive Fetch Response
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
async function getGithubProfile(username) { | |
let response; | |
try { | |
response = await fetch(`https://api.github.com/users/${username}`); | |
} catch (error) { | |
throw new Error(`Network error: ${error.message}`); | |
} | |
if (!response.ok) { | |
const message = `HTTP error! status: ${response.status}`; | |
throw new Error(message); | |
} | |
let data; | |
try { | |
data = await response.json(); | |
} catch (error) { | |
throw new Error(`API response error: ${error.message}`); | |
} | |
if (!data || typeof data !== 'object') { | |
throw new Error('Invalid response format from the API'); | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment