Skip to content

Instantly share code, notes, and snippets.

@richardscarrott
Created January 11, 2016 18:27
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 richardscarrott/3e1b3090cfcae6965efb to your computer and use it in GitHub Desktop.
Save richardscarrott/3e1b3090cfcae6965efb to your computer and use it in GitHub Desktop.
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