Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions packages/sdk/src/http/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { HttpClient } from "./index";
import { Context7Error } from "@error";

describe("HttpClient error handling", () => {
afterEach(() => {
vi.restoreAllMocks();
});

test("throws Context7Error for non-JSON error responses", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("<html>Bad gateway</html>", {
status: 502,
statusText: "Bad Gateway",
headers: { "content-type": "text/html" },
})
);

const client = new HttpClient({
baseUrl: "https://example.com/api",
retry: false,
});

try {
await client.request({ path: ["v2", "libs", "search"] });
throw new Error("Expected request to throw");
} catch (error) {
expect(error).toBeInstanceOf(Context7Error);
expect((error as Error).message).toBe("Bad Gateway");
}
});

test("prefers API error message when response body is JSON", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ error: "rate limit exceeded" }), {
status: 429,
statusText: "Too Many Requests",
headers: { "content-type": "application/json" },
})
);

const client = new HttpClient({
baseUrl: "https://example.com/api",
retry: false,
});

await expect(client.request({ path: ["v2", "libs", "search"] })).rejects.toMatchObject({
message: "rate limit exceeded",
});
});
});
11 changes: 9 additions & 2 deletions packages/sdk/src/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,15 @@ export class HttpClient implements Requester {
}

if (!res.ok) {
const errorBody = (await res.json()) as { error?: string; message?: string };
throw new Context7Error(errorBody.error || errorBody.message || res.statusText);
let errorBody: { error?: string; message?: string } | undefined;

try {
errorBody = (await res.json()) as { error?: string; message?: string };
} catch {
// Non-JSON error responses should still throw a typed Context7Error.
}

throw new Context7Error(errorBody?.error || errorBody?.message || res.statusText);
}

const contentType = res.headers.get("content-type");
Expand Down