Skip to content

Instantly share code, notes, and snippets.

@liuxiaomingskm
Last active February 1, 2020 19:03
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 liuxiaomingskm/b84e99a9c6e6df0965dda050be65d4ab to your computer and use it in GitHub Desktop.
Save liuxiaomingskm/b84e99a9c6e6df0965dda050be65d4ab to your computer and use it in GitHub Desktop.
Fetch Handling Errors(取代XMLHttpRequest的fetch的写法和错误处理方式)
<button>CLICK ME TO MAKE A BAD REQUEST</button>
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var url = 'https://api.github.com/users/coltasdas';
fetch(url)
.then(handleErrors)
.then(function(request){
console.log("EVERYTHING IS FINE!");
console.log(request);
})
.catch(function(error){
console.log(error);
});
});
function handleErrors (request){
if(!request.ok) {
throw Error(request.status);
}
return request;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment