From 08acf86fe3d9c8b97bc9aeac9bd4737d5c5f9311 Mon Sep 17 00:00:00 2001 From: Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com> Date: Fri, 3 Jul 2026 00:19:06 -0300 Subject: [PATCH] fix(api): guard shared API client against non-JSON error responses (#5973) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integrated into release/v3.8.44 — guard shared API client against non-JSON error responses. --- src/shared/utils/api.ts | 4 ++-- tests/unit/shared-api-utils.test.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) 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; + } + ); +});