Skip to content

Instantly share code, notes, and snippets.

@asuh
Created September 14, 2023 23:40
Show Gist options
  • Save asuh/7d3dc277ecdc7d654d8c681bc1b281d3 to your computer and use it in GitHub Desktop.
Save asuh/7d3dc277ecdc7d654d8c681bc1b281d3 to your computer and use it in GitHub Desktop.
Defensive Fetch Response
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