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

Check if baseRequest throws a Response before assuming so

This commit is contained in:
Brett Sun 2016-06-15 14:46:35 +02:00
parent c0ddea975a
commit 685ac0d941

View File

@ -32,12 +32,15 @@ export default function request(url, config) {
.then((apiUrl) => ( .then((apiUrl) => (
baseRequest(apiUrl, requestConfig) baseRequest(apiUrl, requestConfig)
// Catch any errors resulting from baseRequest first // Catch any errors resulting from baseRequest first
.catch((res) => { .catch((err) => {
if (res == null) { if (err == null) {
throw new Error(`For: ${apiUrl} - Server did not respond to the request. ` + throw new Error(`For: ${apiUrl} - Server did not respond to the request. ` +
'(Not even displayed a 500)'); '(Not even displayed a 500)');
} else { } else if (err instanceof Response) {
let err = new Error(`${res.status} - ${res.statusText} - on URL: ${res.url}`); const res = err;
let responseErr = new Error(
`${res.status} - ${res.statusText} - on URL: ${res.url}`
);
// Try to parse the response body to see if we added more descriptive errors // Try to parse the response body to see if we added more descriptive errors
// before rejecting with the error above. // before rejecting with the error above.
@ -45,15 +48,19 @@ export default function request(url, config) {
.json() .json()
.then((body) => { .then((body) => {
if (body && Array.isArray(body.errors) && body.errors.length) { if (body && Array.isArray(body.errors) && body.errors.length) {
err = new Error(body.errors.pop()); responseErr = new Error(body.errors.pop());
} }
// ES6 promises don't have a .finally() clause so we fake that here // ES6 promises don't have a .finally() clause so we fake that here
// by forcing the .catch() clause to run // by forcing the .catch() clause to run
return Promise.reject(); return Promise.reject();
}) })
// If parsing the response body throws, just rethrow the original error // If parsing the response body throws, just rethrow the original
.catch(() => { throw err; }); // response error
.catch(() => { throw responseErr; });
} else {
// Just rethrow the error since it's not a Response
throw err;
} }
}) })
// Handle successful requests // Handle successful requests