Skip to content

Instantly share code, notes, and snippets.

Last active December 18, 2020 18:34
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) {
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('', 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