A Pen by Colt Steele on CodePen.
Last active
February 1, 2020 19:03
-
-
Save liuxiaomingskm/b84e99a9c6e6df0965dda050be65d4ab to your computer and use it in GitHub Desktop.
Fetch Handling Errors(取代XMLHttpRequest的fetch的写法和错误处理方式)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<button>CLICK ME TO MAKE A BAD REQUEST</button> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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