Skip to content

Commit

Permalink
Merge pull request #154 from lodi-g/feature/error-handling-networkReq…
Browse files Browse the repository at this point in the history
…uest

Adds error handling in networkRequest
  • Loading branch information
zemberdotnet authored Oct 26, 2023
2 parents 73d57eb + 2edba6d commit 5969dab
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/networkRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,19 @@ export const networkRequest = async (
url: string,
): Promise<Record<string, unknown>> => {
const result = await fetch(url);

const { status, headers } = result;

if (status < 200 || status >= 300) {
const body = await result.text();
throw new Error(`HTTP request failed (${status}): ${body}`);
}

const contentType = headers.get('content-type');
if (contentType?.includes('application/json') === false) {
const body = await result.text();
throw new Error(`HTTP response is not JSON but ${contentType}: ${body}`);
}

return result.json();
};

0 comments on commit 5969dab

Please sign in to comment.