Skip to content

Instantly share code, notes, and snippets.

@justinnoel
Last active November 13, 2021 12:54
Show Gist options
  • Save justinnoel/57514eba131d8a12f86bb2e399757d5a to your computer and use it in GitHub Desktop.
Save justinnoel/57514eba131d8a12f86bb2e399757d5a to your computer and use it in GitHub Desktop.
Helper function to get JSON data from an API call and handle failures.
export async function getJson(url, options) {
try {
const response = await fetch(url, options);
const contentType = response.headers.get("content-type");
if (! response.ok || ! contentType.includes("application/json")) {
console.log(`ERROR: getJSON -> Invalid Response -> response.status = ${
response.status
}`,);
console.log(`ERROR: getJSON -> Invalid Response ->response.statusText = ${
response.statusText
}`,);
console.log(`ERROR: getJSON -> Invalid Response ->response.contentType = ${contentType}`,);
return {json: null, error: "request failed"};
}
const data = await response.json();
return {data, error: null};
} catch (e) {
console.log(`ERROR: getJSON -> exception -> ${
e.message
}`);
return {data: null, error: "request failed"};
}
const {data, error} = getJson("http://abc123.com");
if (error) {
...return;
}
console.log(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment