fix(moderation): improve error handling for malformed JSON responses and ensure proper response headers

This commit is contained in:
MythEclipse
2026-05-21 04:00:36 +07:00
parent 8884e29ce7
commit f851ea0fa9
2 changed files with 13 additions and 4 deletions
+11 -4
View File
@@ -12,8 +12,6 @@ const openai = new OpenAI({
timeout: 2_147_483_647, timeout: 2_147_483_647,
fetch: async (url, init) => { fetch: async (url, init) => {
const response = await globalThis.fetch(url, init); const response = await globalThis.fetch(url, init);
if (response.headers) return response;
const body = const body =
typeof response.text === "function" typeof response.text === "function"
? await response.text() ? await response.text()
@@ -23,14 +21,23 @@ const openai = new OpenAI({
if (response.ok !== false) { if (response.ok !== false) {
try { try {
JSON.parse(body); 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)); normalizedBody = JSON.stringify(extractJson(body));
} }
} }
return new Response(normalizedBody, { return new Response(normalizedBody, {
status: response.status ?? 200, status: response.status ?? 200,
headers: { "Content-Type": "application/json" }, headers: response.headers ?? { "Content-Type": "application/json" },
}); });
}, },
}); });
@@ -540,6 +540,8 @@ describe("runModerationAnalysis", () => {
global.fetch = vi.fn().mockResolvedValue({ global.fetch = vi.fn().mockResolvedValue({
ok: true, ok: true,
status: 200,
headers: new Headers({ "Content-Type": "application/json" }),
text: async () => `${JSON.stringify(mockResponse)}\nextra`, text: async () => `${JSON.stringify(mockResponse)}\nextra`,
}); });