Skip to content

Commit

Permalink
Handle http errors
Browse files Browse the repository at this point in the history
  • Loading branch information
typeofweb committed Nov 1, 2023
1 parent e3197cc commit c59b35a
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/lib/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ export async function executeGraphQL<Result, Variables>(
next: { revalidate },
});

if (!response.ok) {
const body = await (async () => {
try {
return await response.text();
} catch {
return "";
}
})();
throw new HTTPError(response, body);
}

const body = (await response.json()) as GraphQLRespone<Result>;

if ("errors" in body) {
Expand All @@ -55,6 +66,14 @@ export class GraphQLError extends Error {
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class HTTPError extends Error {
constructor(response: Response, body: string) {
const message = `HTTP error ${response.status}: ${response.statusText}\n${body}`;
super(message);
this.name = this.constructor.name;
Object.setPrototypeOf(this, new.target.prototype);
}
}

export const formatMoney = (amount: number, currency: string) =>
new Intl.NumberFormat("en-US", {
Expand Down

0 comments on commit c59b35a

Please sign in to comment.