Skip to content

Instantly share code, notes, and snippets.

@zarcode
Last active November 9, 2019 07:53
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 zarcode/e72c644ea309cf8b2e989a08c3247beb to your computer and use it in GitHub Desktop.
Save zarcode/e72c644ea309cf8b2e989a08c3247beb to your computer and use it in GitHub Desktop.
fetch with status code handling
async function asyncCall() {
let response = await fetch("https://httpstat.us/500")
if (response.ok) return await response.text()
throw new Error(response)
}
async function callFetch() {
try {
let const = await asyncCall()
console.log(text)
} catch(e) {
console.log("error", e);
}
}
callFetch();
function syncCall() {
fetch("https://httpstat.us/500")
.then(function(response) {
if (!response.ok) {
throw Error(response);
}
return response;
})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log("ok", text);
})
.catch(function(error) {
console.log("error", error);
})
}
syncCall();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment