tfrere's picture
tfrere HF Staff
Cursor
feat(embed-studio): error loop, versions, chips and preview controls
461e15a
Raw History Blame Contribute Delete
1.94 kB
/**
* Turn an inference failure into the one-line message the chat UI shows.
*
* Provider errors (AI SDK `APICallError`) carry the HTTP status of the
* Inference Providers router. We keep it as an `HTTP <code>:` prefix so the
* client can map 401 / 402 / 429 to an actionable message without parsing
* provider-specific wording, and we pull the human part out of JSON bodies.
*/
export function formatStreamError(error: unknown): string {
const status = statusOf(error);
const message = cleanMessage(error);
return status ? `HTTP ${status}: ${message}` : message;
}
function statusOf(error: unknown): number | null {
if (!error || typeof error !== "object") return null;
const e = error as { statusCode?: unknown; status?: unknown; cause?: unknown };
const code = typeof e.statusCode === "number" ? e.statusCode : typeof e.status === "number" ? e.status : null;
if (code) return code;
return e.cause && e.cause !== error ? statusOf(e.cause) : null;
}
function cleanMessage(error: unknown): string {
if (!error) return "Stream error";
const e = error as { message?: unknown; responseBody?: unknown };
const body = typeof e.responseBody === "string" ? fromJson(e.responseBody) : null;
if (body) return body;
const raw = typeof e.message === "string" && e.message ? e.message : String(error);
return fromJson(raw) ?? raw;
}
function fromJson(text: string): string | null {
const trimmed = text.trim();
if (!trimmed.startsWith("{")) return null;
try {
const parsed = JSON.parse(trimmed) as { error?: unknown; message?: unknown };
const inner = parsed.error;
if (typeof inner === "string") return inner;
if (inner && typeof inner === "object" && typeof (inner as { message?: unknown }).message === "string") {
return (inner as { message: string }).message;
}
if (typeof parsed.message === "string") return parsed.message;
} catch {
return null;
}
return null;
}