Skip to content
Merged
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
5 changes: 3 additions & 2 deletions shared/hooks/use-general-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from "preact/hooks";
import { extractErrorMessage } from "../utils/extract-error";

export interface GeneralSettingsData {
port: number;
Expand Down Expand Up @@ -54,8 +55,8 @@ export function useGeneralSettings(apiKey: string | null) {
body: JSON.stringify(patch),
});
if (!resp.ok) {
const body = await resp.json().catch(() => ({ error: `HTTP ${resp.status}` }));
throw new Error((body as { error?: string }).error ?? `HTTP ${resp.status}`);
const body = await resp.json().catch(() => null);
throw new Error(extractErrorMessage(body, `HTTP ${resp.status}`));
}
const result = await resp.json() as GeneralSettingsSaveResponse;
setData({
Expand Down
5 changes: 3 additions & 2 deletions shared/hooks/use-quota-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from "preact/hooks";
import { extractErrorMessage } from "../utils/extract-error";

export interface QuotaSettingsData {
refresh_interval_minutes: number;
Expand Down Expand Up @@ -40,8 +41,8 @@ export function useQuotaSettings(apiKey: string | null) {
body: JSON.stringify(patch),
});
if (!resp.ok) {
const body = await resp.json().catch(() => ({ error: `HTTP ${resp.status}` }));
throw new Error((body as { error?: string }).error ?? `HTTP ${resp.status}`);
const body = await resp.json().catch(() => null);
throw new Error(extractErrorMessage(body, `HTTP ${resp.status}`));
}
const result = await resp.json() as { success: boolean } & QuotaSettingsData;
setData({
Expand Down
5 changes: 3 additions & 2 deletions shared/hooks/use-rotation-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from "preact/hooks";
import { extractErrorMessage } from "../utils/extract-error";

export type RotationStrategy = "least_used" | "round_robin" | "sticky";

Expand Down Expand Up @@ -39,8 +40,8 @@ export function useRotationSettings(apiKey: string | null) {
body: JSON.stringify(patch),
});
if (!resp.ok) {
const body = await resp.json().catch(() => ({ error: `HTTP ${resp.status}` }));
throw new Error((body as { error?: string }).error ?? `HTTP ${resp.status}`);
const body = await resp.json().catch(() => null);
throw new Error(extractErrorMessage(body, `HTTP ${resp.status}`));
}
const result = await resp.json() as { success: boolean } & RotationSettingsData;
setData({ rotation_strategy: result.rotation_strategy });
Expand Down
5 changes: 3 additions & 2 deletions shared/hooks/use-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from "preact/hooks";
import { extractErrorMessage } from "../utils/extract-error";

export function useSettings() {
const [apiKey, setApiKey] = useState<string | null>(null);
Expand Down Expand Up @@ -36,8 +37,8 @@ export function useSettings() {
body: JSON.stringify({ proxy_api_key: newKey }),
});
if (!resp.ok) {
const data = await resp.json().catch(() => ({ error: `HTTP ${resp.status}` }));
throw new Error((data as { error?: string }).error ?? `HTTP ${resp.status}`);
const body = await resp.json().catch(() => null);
throw new Error(extractErrorMessage(body, `HTTP ${resp.status}`));
}
const result: { proxy_api_key: string | null } = await resp.json();
setApiKey(result.proxy_api_key);
Expand Down
32 changes: 32 additions & 0 deletions shared/utils/__tests__/extract-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it, expect } from "vitest";
import { extractErrorMessage } from "../extract-error";

describe("extractErrorMessage", () => {
it("extracts from flat admin format: { error: 'string' }", () => {
expect(extractErrorMessage({ error: "Invalid current API key" }, "fallback"))
.toBe("Invalid current API key");
});

it("extracts from nested OpenAI format: { error: { message: '...' } }", () => {
expect(extractErrorMessage(
{ error: { message: "Config validation failed", type: "server_error", param: null, code: "internal_error" } },
"fallback",
)).toBe("Config validation failed");
});

it("returns fallback for null body", () => {
expect(extractErrorMessage(null, "HTTP 500")).toBe("HTTP 500");
});

it("returns fallback for empty object", () => {
expect(extractErrorMessage({}, "HTTP 500")).toBe("HTTP 500");
});

it("returns fallback for body with non-string, non-object error", () => {
expect(extractErrorMessage({ error: 42 }, "HTTP 500")).toBe("HTTP 500");
});

it("returns fallback when nested error.message is not a string", () => {
expect(extractErrorMessage({ error: { message: 123 } }, "HTTP 500")).toBe("HTTP 500");
});
});
21 changes: 21 additions & 0 deletions shared/utils/extract-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Extract a human-readable error message from an API error response body.
*
* Handles both formats:
* - Admin endpoints (flat): { error: "message" }
* - OpenAI error handler: { error: { message: "..." } }
*/
export function extractErrorMessage(
body: unknown,
fallback: string,
): string {
if (body && typeof body === "object" && "error" in body) {
const err = (body as Record<string, unknown>).error;
if (typeof err === "string") return err;
if (err && typeof err === "object" && "message" in err) {
const msg = (err as Record<string, unknown>).message;
if (typeof msg === "string") return msg;
}
}
return fallback;
}
1 change: 1 addition & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export default defineConfig({
environment: "node",
include: [
"src/**/*.{test,spec}.ts",
"shared/**/*.{test,spec}.ts",
"tests/unit/**/*.{test,spec}.ts",
"tests/integration/**/*.{test,spec}.ts",
"packages/electron/__tests__/**/*.{test,spec}.ts",
Expand Down
Loading