Skip to content

Commit

Permalink
Allow nested errors in non-2xx response (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
leo authored Jul 15, 2024
1 parent 699679b commit fcd2350
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,30 @@ export const getResponseBody = async <T>(
response: Response,
options?: { errorPrefix?: string },
): Promise<T> => {
// If the response is okay, we want to parse the JSON asynchronously.
if (response.ok) return response.json() as T;

const text = await response.text();

let error: InvalidResponseErrorDetails = {
message: text,
code: 'UNKNOWN_ERROR',
let json: T & {
error?: InvalidResponseErrorDetails;
};

try {
({ error } = JSON.parse(text));
json = JSON.parse(text);
} catch (err) {
// Ignore parsing errors
throw new InvalidResponseError({
message: `${options?.errorPrefix ? `${options.errorPrefix} ` : ``}${text}`,
code: 'JSON_PARSE_ERROR',
});
}

if (options?.errorPrefix) error.message = `${options.errorPrefix} ${error.message}`;
if (json.error) {
json.error.message = `${options?.errorPrefix ? `${options.errorPrefix} ` : ``}${json.error.message}`;
throw new InvalidResponseError(json.error);
}

throw new InvalidResponseError(error);
return json;
};

/**
Expand Down

0 comments on commit fcd2350

Please sign in to comment.