From f851ea0fa9b2e41d05c396dc7bfead8231455dc2 Mon Sep 17 00:00:00 2001 From: MythEclipse Date: Thu, 21 May 2026 04:00:36 +0700 Subject: [PATCH] fix(moderation): improve error handling for malformed JSON responses and ensure proper response headers --- src/moderation/llmModerationClient.ts | 15 +++++++++++---- tests/moderation/llmModerationClient.test.ts | 2 ++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/moderation/llmModerationClient.ts b/src/moderation/llmModerationClient.ts index 63234eb..2bccb3f 100644 --- a/src/moderation/llmModerationClient.ts +++ b/src/moderation/llmModerationClient.ts @@ -12,8 +12,6 @@ const openai = new OpenAI({ timeout: 2_147_483_647, fetch: async (url, init) => { const response = await globalThis.fetch(url, init); - if (response.headers) return response; - const body = typeof response.text === "function" ? await response.text() @@ -23,14 +21,23 @@ const openai = new OpenAI({ if (response.ok !== false) { try { JSON.parse(body); - } catch { + } catch (error) { + log.warn( + { + error: error instanceof Error ? error.message : String(error), + status: response.status ?? 200, + bodyLength: body.length, + body, + }, + "LLM provider returned malformed JSON response body", + ); normalizedBody = JSON.stringify(extractJson(body)); } } return new Response(normalizedBody, { status: response.status ?? 200, - headers: { "Content-Type": "application/json" }, + headers: response.headers ?? { "Content-Type": "application/json" }, }); }, }); diff --git a/tests/moderation/llmModerationClient.test.ts b/tests/moderation/llmModerationClient.test.ts index 6f0fb0a..eca4ecf 100644 --- a/tests/moderation/llmModerationClient.test.ts +++ b/tests/moderation/llmModerationClient.test.ts @@ -540,6 +540,8 @@ describe("runModerationAnalysis", () => { global.fetch = vi.fn().mockResolvedValue({ ok: true, + status: 200, + headers: new Headers({ "Content-Type": "application/json" }), text: async () => `${JSON.stringify(mockResponse)}\nextra`, });