diff --git a/src/shared/utils/api.ts b/src/shared/utils/api.ts index f15eff16b3..852091b772 100644 --- a/src/shared/utils/api.ts +++ b/src/shared/utils/api.ts @@ -96,10 +96,10 @@ export function getErrorMessage( } async function handleResponse(response: Response) { - const data = await response.json(); + const data = await parseResponseBody(response); if (!response.ok) { - const error: any = new Error(data.error || "An error occurred"); + const error: any = new Error(getErrorMessage(data, response.status, "An error occurred")); error.status = response.status; error.data = data; throw error; diff --git a/tests/unit/shared-api-utils.test.ts b/tests/unit/shared-api-utils.test.ts index 56b8f709a0..a91e5973cf 100644 --- a/tests/unit/shared-api-utils.test.ts +++ b/tests/unit/shared-api-utils.test.ts @@ -109,3 +109,22 @@ test("shared api utils throw enriched errors for non-OK responses", async () => } ); }); + +test("shared api utils throw a clean error for non-JSON non-OK responses", async () => { + globalThis.fetch = async () => + new Response("Bad Gateway", { + status: 502, + headers: { "Content-Type": "text/plain" }, + }); + + await assert.rejects( + () => get("http://localhost/get"), + (error) => { + assert.ok(!(error instanceof SyntaxError), "must not be a raw JSON parse SyntaxError"); + assert.match((error as any).message, /Bad Gateway/); + assert.equal((error as any).status, 502); + assert.equal((error as any).data, "Bad Gateway"); + return true; + } + ); +});