Skip to content

Commit

Permalink
Add basic API error handling for HTTP client
Browse files Browse the repository at this point in the history
  • Loading branch information
thibaudcolas committed Jan 25, 2017
1 parent d3a582a commit 67fc4c5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
4 changes: 2 additions & 2 deletions client/src/api/admin.js
Expand Up @@ -13,11 +13,11 @@ export const getChildPages = (id, options = {}) => {
url += `&${options.filter}`;
}

return get(url);
return get(url).then(res => res.body);
};

export const getPage = (id) => {
const url = `${ADMIN_API.PAGES}${id}/`;

return get(url);
return get(url).then(res => res.body);
};
28 changes: 25 additions & 3 deletions client/src/api/client.js
@@ -1,9 +1,13 @@
import _ from 'lodash';

const fetch = global.fetch;

// fetch wrapper for JSON APIs.
export const get = (url) => {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json',
});

const options = {
credentials: 'same-origin',
Expand All @@ -12,5 +16,23 @@ export const get = (url) => {
};

return fetch(url, options)
.then(response => response.json());
.then((res) => {
const response = {
status: res.status,
statusText: res.statusText,
headers: res.headers
};

let ret;
if (response.status >= 200 && response.status < 300) {
ret = res.json().then(json => _.assign(response, { body: json }));
} else {
ret = res.text().then((text) => {
const err = _.assign(new Error(response.statusText), response, { body: text });
throw err;
});
}

return ret;
});
};

0 comments on commit 67fc4c5

Please sign in to comment.