Skip to content

Instantly share code, notes, and snippets.

@MoritzKn
Last active December 18, 2020 18:34
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 MoritzKn/15bf9b8ecac66de030874d41edc22858 to your computer and use it in GitHub Desktop.
Save MoritzKn/15bf9b8ecac66de030874d41edc22858 to your computer and use it in GitHub Desktop.
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