Skip to content

Instantly share code, notes, and snippets.

@MoritzKn
Last active Dec 18, 2020
Embed
What would you like to do?
Fetch and validate JSON (the fetch wrapper that I write over and over again)
async function fetchJson(url, options, validate) {
const response = await fetch(url, options);
let json;
let jsonError;
try {
json = await response.json();
} catch (error) {
jsonError = error;
}
if (json && validate) {
validate(json);
return json;
}
if (!response.ok) {
throw new Error(`Unexpected Status: ${response.status}`);
}
if (json) {
return json;
}
throw jsonError;
}
// Use like this:
const json = await fetchJson('https://api.github.com/users/MoritzKn', null, (json) => {
if (json.message) {
throw new Error(json.message);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment