Skip to content

Context7 Platform -- Up-to-date docs for AI agents

fix(sdk): avoid raw SyntaxError on non-JSON error responses (#2732)

Fahreddin Özcanf327589a9a11
diff --git a/.changeset/sdk-non-json-error-response.md b/.changeset/sdk-non-json-error-response.md
new file mode 100644
index 00000000..96cd84f5
--- /dev/null
+++ b/.changeset/sdk-non-json-error-response.md
@@ -0,0 +1,5 @@
+---
+"@upstash/context7-sdk": patch
+---
+
+Avoid throwing a raw `SyntaxError` when the server returns a non-JSON error body. `HttpClient.request()` now wraps the error-path `res.json()` in a `.catch`, so non-JSON responses (HTML 502s, plain-text 429s, Cloudflare challenge pages) fall back to `res.statusText` and always surface as a typed `Context7Error`.
diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.ts
index f1986a71..65140847 100644
--- a/packages/cli/src/__tests__/auth-utils.test.ts
+++ b/packages/cli/src/__tests__/auth-utils.test.ts
@@ -1,7 +1,5 @@
import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
-vi.mock("os", () => ({ homedir: () => "/fake-home", default: { homedir: () => "/fake-home" } }));
-
vi.mock("fs", () => {
const fns = {
existsSync: vi.fn(),
@@ -37,6 +35,13 @@ const CONFIG_DIR_PATH = "/fake-home/.config/context7";
beforeEach(() => {
vi.clearAllMocks();
+ // os.homedir() reads $HOME first on POSIX, so stubbing the env var pins the
+ // home directory deterministically without mocking the `os` builtin (which
+ // resolves unreliably across Node versions / worker pooling in CI).
+ vi.stubEnv("HOME", "/fake-home");
+ vi.stubEnv("XDG_CONFIG_HOME", undefined);
+ vi.stubEnv("XDG_STATE_HOME", undefined);
+ vi.stubEnv("XDG_CACHE_HOME", undefined);
vi.stubGlobal(
"fetch",
vi.fn(() => {
@@ -335,14 +340,13 @@ describe("startDeviceAuthorization", () => {
});
vi.stubGlobal("fetch", fetchMock);
await startDeviceAuthorization("https://t.example", "test-client");
- expect(fetchMock).toHaveBeenCalledWith(
- "https://t.example/api/oauth/device/code",
- expect.objectContaining({
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: "client_id=test-client",
- })
- );
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe("https://t.example/api/oauth/device/code");
+ expect(init.method).toBe("POST");
+ expect(init.headers).toEqual({ "Content-Type": "application/x-www-form-urlencoded" });
+ // Body is form-encoded; hostname is appended best-effort and varies by
+ // machine, so assert on the parsed client_id rather than the exact string.
+ expect(new URLSearchParams(init.body as string).get("client_id")).toBe("test-client");
});
test("throws with the server-provided error_description", async () => {
diff --git a/packages/cli/src/__tests__/storage-paths.test.ts b/packages/cli/src/__tests__/storage-paths.test.ts
index 16612ce9..05933676 100644
--- a/packages/cli/src/__tests__/storage-paths.test.ts
+++ b/packages/cli/src/__tests__/storage-paths.test.ts
@@ -13,10 +13,13 @@ import {
const HOME = "/fake-home";
beforeEach(() => {
- vi.mock("os", async () => {
- const actual = await vi.importActual<typeof import("os")>("os");
- return { ...actual, homedir: () => HOME };
- });
+ // os.homedir() reads $HOME first on POSIX, so stubbing the env var pins the
+ // home directory deterministically without mocking the `os` builtin (which
+ // resolves unreliably across Node versions / worker pooling in CI).
+ vi.stubEnv("HOME", HOME);
+ vi.stubEnv("XDG_CONFIG_HOME", undefined);
+ vi.stubEnv("XDG_STATE_HOME", undefined);
+ vi.stubEnv("XDG_CACHE_HOME", undefined);
});
afterEach(() => {
diff --git a/packages/sdk/src/http/index.test.ts b/packages/sdk/src/http/index.test.ts
new file mode 100644
index 00000000..1d0d0209
--- /dev/null
+++ b/packages/sdk/src/http/index.test.ts
@@ -0,0 +1,81 @@
+import { describe, test, expect, vi, afterEach } from "vitest";
+import { HttpClient } from "./index";
+import { Context7Error } from "@error";
+
+function newClient(): HttpClient {
+ return new HttpClient({
+ baseUrl: "https://example.com/api",
+ retry: false,
+ });
+}
+
+function mockFetch(response: Response) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => Promise.resolve(response))
+ );
+}
+
+describe("HttpClient error handling", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ test("throws Context7Error with message from JSON error body", async () => {
+ mockFetch(
+ new Response(JSON.stringify({ error: "rate limit exceeded" }), {
+ status: 429,
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ await expect(newClient().request({ path: ["search"] })).rejects.toThrowError(
+ new Context7Error("rate limit exceeded")
+ );
+ });
+
+ test("falls back to message field when error field is absent", async () => {
+ mockFetch(
+ new Response(JSON.stringify({ message: "something went wrong" }), {
+ status: 400,
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ const error = await newClient()
+ .request({ path: ["search"] })
+ .catch((e) => e);
+
+ expect(error).toBeInstanceOf(Context7Error);
+ expect(error.message).toBe("something went wrong");
+ });
+
+ test("throws Context7Error (not SyntaxError) on non-JSON error body", async () => {
+ mockFetch(
+ new Response("<html><body>502 Bad Gateway</body></html>", {
+ status: 502,
+ statusText: "Bad Gateway",
+ headers: { "content-type": "text/html" },
+ })
+ );
+
+ const error = await newClient()
+ .request({ path: ["search"] })
+ .catch((e) => e);
+
+ expect(error).toBeInstanceOf(Context7Error);
+ expect(error).not.toBeInstanceOf(SyntaxError);
+ expect(error.message).toBe("Bad Gateway");
+ });
+
+ test("falls back to statusText on empty error body", async () => {
+ mockFetch(new Response("", { status: 503, statusText: "Service Unavailable" }));
+
+ const error = await newClient()
+ .request({ path: ["search"] })
+ .catch((e) => e);
+
+ expect(error).toBeInstanceOf(Context7Error);
+ expect(error.message).toBe("Service Unavailable");
+ });
+});
diff --git a/packages/sdk/src/http/index.ts b/packages/sdk/src/http/index.ts
index 10d7e33f..3f453eae 100644
--- a/packages/sdk/src/http/index.ts
+++ b/packages/sdk/src/http/index.ts
@@ -169,7 +169,10 @@ export class HttpClient implements Requester {
}
if (!res.ok) {
- const errorBody = (await res.json()) as { error?: string; message?: string };
+ const errorBody = (await res.json().catch(() => ({}))) as {
+ error?: string;
+ message?: string;
+ };
throw new Context7Error(errorBody.error || errorBody.message || res.statusText);
}