fix(api): surface non-json error messages

This commit is contained in:
zetaloop
2026-02-28 14:27:43 +08:00
parent 7d10be1c1f
commit f085a49d87
+9 -6
View File
@@ -6,14 +6,14 @@ type JsonRequestInit = Omit<RequestInit, "body" | "headers"> & {
json?: unknown json?: unknown
} }
async function readJsonBody(res: Response): Promise<unknown | null> { async function readJsonBody(res: Response): Promise<{ json: unknown | null; text: string }> {
const text = await res.text() const text = await res.text()
if (!text) return null if (!text) return { json: null, text: "" }
try { try {
return JSON.parse(text) as unknown return { json: JSON.parse(text) as unknown, text }
} catch { } catch {
return null return { json: null, text }
} }
} }
@@ -64,7 +64,7 @@ export async function httpJson<T>(path: string, init?: JsonRequestInit): Promise
body, body,
}) })
const data = await readJsonBody(res) const { json: data, text } = await readJsonBody(res)
if (res.ok) { if (res.ok) {
return data as T return data as T
@@ -83,5 +83,8 @@ export async function httpJson<T>(path: string, init?: JsonRequestInit): Promise
throw apiError throw apiError
} }
throw { code: res.status, msg: res.statusText || "Request failed" } satisfies ApiError throw {
code: res.status,
msg: text || res.statusText || "Request failed",
} satisfies ApiError
} }