From c59b35ad1b0d8868a382643556197592931f3c2b Mon Sep 17 00:00:00 2001 From: Michal Miszczyszyn Date: Wed, 1 Nov 2023 02:13:24 +0100 Subject: [PATCH] Handle http errors --- src/lib/graphql.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/lib/graphql.ts b/src/lib/graphql.ts index 5a9865bf8..540c8de1c 100644 --- a/src/lib/graphql.ts +++ b/src/lib/graphql.ts @@ -38,6 +38,17 @@ export async function executeGraphQL( 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; if ("errors" in body) { @@ -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", {