Skip to content

Commit

Permalink
fix(fetch): prefer JSON errors where possible
Browse files Browse the repository at this point in the history
  • Loading branch information
gadicc committed Jan 29, 2021
1 parent 5b6eac4 commit 2b14f15
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
3 changes: 2 additions & 1 deletion src/lib/errors.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
class BadRequestError extends Error {}
class HTTPError extends Error {}

module.exports = { BadRequestError };
module.exports = { BadRequestError, HTTPError };
30 changes: 19 additions & 11 deletions src/lib/yahooFinanceFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,11 @@ async function yahooFinanceFetch(urlBase, params={}, fetchOptionsOverrides={}, f
};

const res = await fetch(url, fetchOptions);
if (!res.ok) {
console.error(url);
throw new Error("Error " + res.status + ": " + res.statusText)
}

const result = await res[func]();

/*
{
finance: {
finance: { // or quoteSummary, or any other single key
result: null,
error: {
code: 'Bad Request',
Expand All @@ -38,11 +33,24 @@ async function yahooFinanceFetch(urlBase, params={}, fetchOptionsOverrides={}, f
}
}
*/
if (func==='json' && result.finance && result.finance.error) {
const errorObj = result.finance.error;
const errorName = errorObj.code.replace(/ /g, '') + 'Error';
const ErrorClass = errors[errorName] || Error;
throw new ErrorClass(errorObj.description);
if (func==='json') {
const keys = Object.keys(result);
if (keys.length === 1) {
const errorObj = result[keys[0]].error;
if (errorObj) {
const errorName = errorObj.code.replace(/ /g, '') + 'Error';
const ErrorClass = errors[errorName] || Error;
throw new ErrorClass(errorObj.description);
}
}
}

// We do this last as it generally contains less information (e.g. no desc).
if (!res.ok) {
console.error(url);
const error = new errors.HTTPError(res.statusText);
error.code = res.status;
throw new error;
}

return result;
Expand Down

0 comments on commit 2b14f15

Please sign in to comment.