fix(providers): add safe json response helper

This commit is contained in:
Vincent Koc
2026-05-15 08:41:03 +08:00
parent a709927698
commit d16f79f49d
3 changed files with 21 additions and 0 deletions
+12
View File
@@ -4,6 +4,7 @@ import {
assertOkOrThrowHttpError,
extractProviderErrorDetail,
extractProviderRequestId,
readProviderJsonResponse,
} from "./provider-http-errors.js";
describe("provider error utils", () => {
@@ -54,4 +55,15 @@ describe("provider error utils", () => {
"Legacy provider error (HTTP 400): Bad request [code=invalid_request] [request_id=req_legacy]",
);
});
it("wraps malformed successful JSON responses with provider labels", async () => {
const response = new Response("{ nope", {
status: 200,
headers: { "content-type": "application/json" },
});
await expect(readProviderJsonResponse(response, "Provider catalog failed")).rejects.toThrow(
"Provider catalog failed: malformed JSON response",
);
});
});
+8
View File
@@ -163,3 +163,11 @@ export async function assertOkOrThrowHttpError(response: Response, label: string
}
throw await createProviderHttpError(response, label, { statusPrefix: "HTTP " });
}
export async function readProviderJsonResponse<T>(response: Response, label: string): Promise<T> {
try {
return (await response.json()) as T;
} catch (cause) {
throw new Error(`${label}: malformed JSON response`, { cause });
}
}
+1
View File
@@ -9,6 +9,7 @@ export {
extractProviderRequestId,
formatProviderErrorPayload,
formatProviderHttpErrorMessage,
readProviderJsonResponse,
readResponseTextLimited,
truncateErrorDetail,
} from "../agents/provider-http-errors.js";