Created
March 6, 2019 01:21
-
-
Save NotWoods/fa7b3baf085834ddd29c59c5415bf816 to your computer and use it in GitHub Desktop.
fetch(): reject when response status is not ok
This file contains hidden or 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
/** | |
* Check for any HTTP errors, and throw if one is encountered. | |
* Use as a callback for `fetch` to seamlessly add HTTP error checking to your code. | |
* @param {Response} response | |
* @example | |
* fetch('https://example.com') | |
* .then(checkForHttpErrors) | |
* .then(res => res.json()) | |
* .catch(err => { /* process network error or HTTP error */ }); | |
*/ | |
function checkForHttpErrors(response) { | |
if (response.ok) return response; | |
else throw new HttpError(response); | |
} | |
class HttpError extends Error { | |
/** | |
* @param {Response} response | |
*/ | |
constructor(response) { | |
super(response.statusText); | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, HttpError); | |
} | |
this.response = response; | |
this.status = response.status; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment