1
0
mirror of https://github.com/ascribe/onion.git synced 2024-12-22 17:33:14 +01:00

Simplify error handling in requests

This commit is contained in:
Brett Sun 2016-03-10 12:16:30 +01:00
parent 30ba85d937
commit 8952a607b7

View File

@ -13,11 +13,11 @@ class Requests {
unpackResponse(url) { unpackResponse(url) {
return (response) => { return (response) => {
if (response == null) { if (response == null) {
throw new Error('For: ' + url + ' - Server did not respond to the request. (Not even displayed a 500)'); throw new Error(`For: ${url} - Server did not respond to the request. (Not even displayed a 500)`);
} }
if (response.status >= 500) { if (response.status >= 500) {
let err = new Error(response.status + ' - ' + response.statusText + ' - on URL:' + response.url); let err = new Error(`${response.status} - ${response.statusText} - on URL: ${response.url}`);
return response return response
.text() .text()
@ -25,11 +25,11 @@ class Requests {
const resJson = JSON.parse(resText); const resJson = JSON.parse(resText);
err = new Error(resJson.errors.pop()); err = new Error(resJson.errors.pop());
// ES6 promises don't have a .finally() clause so // ES6 promises don't have a .finally() clause so we fake that here by
// we fake that here by forcing the .catch() clause // forcing the .catch() clause to run
// to run
return Promise.reject(); return Promise.reject();
}) })
// If parsing the resText throws, just rethrow the original error we created
.catch(() => { throw err; }); .catch(() => { throw err; });
} }
@ -42,15 +42,16 @@ class Requests {
if (responseText && responseText !== 'None') { if (responseText && responseText !== 'None') {
const body = JSON.parse(responseText); const body = JSON.parse(responseText);
if(body && body.errors) { if (body && body.errors) {
let error = new Error('Form Error'); const error = new Error('Form Error');
error.json = body; error.json = body;
reject(error); reject(error);
} else if(body && body.detail) { } else if (body && body.detail) {
reject(new Error(body.detail)); reject(new Error(body.detail));
} else if('success' in body && !body.success) { } else if (body && 'success' in body && !body.success) {
let error = new Error('Client Request Error'); const error = new Error('Client Request Error');
error.json = { error.json = {
body: body,
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
type: response.type, type: response.type,
@ -60,13 +61,10 @@ class Requests {
} else { } else {
resolve(body); resolve(body);
} }
} else if (response.status >= 400) {
reject(new Error(`${response.status} - ${response.statusText} - on URL: ${response.url}`));
} else { } else {
if(response.status >= 400) { resolve({});
reject(new Error(response.status + ' - ' + response.statusText + ' - on URL:' + response.url));
} else {
resolve({});
}
} }
}).catch(reject); }).catch(reject);
}); });