Skip to content

Instantly share code, notes, and snippets.

@NotWoods
Created March 6, 2019 01:21
Show Gist options
  • Save NotWoods/fa7b3baf085834ddd29c59c5415bf816 to your computer and use it in GitHub Desktop.
Save NotWoods/fa7b3baf085834ddd29c59c5415bf816 to your computer and use it in GitHub Desktop.
fetch(): reject when response status is not ok
/**
* 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