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
54 changes: 54 additions & 0 deletions src/utils/http-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,57 @@ describe("http-client", () => {
expect(BASE_URL).toBe("https://magic.21st.dev");
});
});

describe("http-client error handling", () => {
let originalFetch: typeof fetch;

beforeEach(() => {
originalFetch = globalThis.fetch;
});

afterEach(() => {
globalThis.fetch = originalFetch;
});

it("throws on non-2xx response with status and error message", async () => {
const { twentyFirstClient } = await import("./http-client.js");

globalThis.fetch = async () =>
new Response(JSON.stringify({ error: "Anthropic experiencing high load" }), {
status: 500,
statusText: "Internal Server Error",
}) as Response;

await expect(
twentyFirstClient.post("/api/refine-ui", { foo: "bar" })
).rejects.toThrow("HTTP 500 Internal Server Error: {\"error\":\"Anthropic experiencing high load\"}");
});

it("throws on non-2xx response when response has no body", async () => {
const { twentyFirstClient } = await import("./http-client.js");

globalThis.fetch = async () =>
new Response(null, {
status: 503,
statusText: "Service Unavailable",
}) as Response;

await expect(
twentyFirstClient.post("/api/refine-ui", { foo: "bar" })
).rejects.toThrow("HTTP 503 Service Unavailable");
});

it("throws on 401 with the error body from server", async () => {
const { twentyFirstClient } = await import("./http-client.js");

globalThis.fetch = async () =>
new Response(JSON.stringify({ error: "Invalid or inactive API key" }), {
status: 401,
statusText: "Unauthorized",
}) as Response;

await expect(
twentyFirstClient.get("/api/some-endpoint")
).rejects.toThrow("HTTP 401 Unauthorized: {\"error\":\"Invalid or inactive API key\"}");
});
});
8 changes: 8 additions & 0 deletions src/utils/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ const createMethod = (method: HttpMethod) => {
});

console.log("response", response);

if (!response.ok) {
const errorText = await response.text().catch(() => "");
throw new Error(
`HTTP ${response.status} ${response.statusText}${errorText ? `: ${errorText}` : ""}`
);
}

return { status: response.status, data: (await response.json()) as T };
};
};
Expand Down