Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wrapper around `window.fetch`
'use strict';
// http://stackoverflow.com/questions/31089801/extending-error-in-javascript-with-es6-syntax
class ExtendableError extends Error {
constructor(message) {
super();
this.message = message;
this.stack = (new Error()).stack;
this.name = this.constructor.name;
}
}
class NetworkError extends ExtendableError {
constructor(message, status, json = {}) {
super(message);
this.status = status;
this.response = json;
}
}
export default NetworkError;
import NetworkError from '../utils/NetworkError';
function checkStatus(response) {
if (response.ok) {
return response;
}
throw response;
};
function parseJson(response) {
if (response.status === 201 || response.status === 204) {
return {};
}
return response.json();
};
function parseError(response) {
// Handle HTTP error statuses
if (response && typeof response.json === 'function') {
return parseJson(response)
.then(json => {
throw new NetworkError(response.statusText, response.status, json);
}, () => {
throw new NetworkError(response.statusText, response.status);
});
}
// Handle Network errors, e.g. cors etc.
throw new NetworkError(response.message);
}
function xhr(url, params = {}) {
params = Object.assign({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, params);
return fetch(url, params)
.then(checkStatus)
.then(parseJson, parseError);
};
export default xhr;
// Usage:
// xhr('/Users').then((data) => { console.log('success', data); }, (error) => { console.log('error', error); }).catch((error) => { console.log('runtime error', error); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.