app-template/app/web/src/lib/trpc-error.ts

27 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** tRPC 错误 → 用户可读文案:提取 zod 数组消息、兜底 HTML/网络异常。 */
export function formatTrpcError(err: unknown, fallback: string): string {
const raw = err instanceof Error ? err.message : typeof err === "string" ? err : "";
if (!raw) return fallback;
if (raw.startsWith("<") || raw.includes("<!DOCTYPE")) {
return "服务暂时不可用,请稍后重试";
}
try {
const parsed: unknown = JSON.parse(raw);
if (Array.isArray(parsed)) {
const msgs = parsed
.map((e) =>
e && typeof e === "object" ? (e as { message?: unknown }).message : null,
)
.filter((m): m is string => typeof m === "string" && m.length > 0);
if (msgs.length > 0) return msgs.join(";");
}
if (parsed && typeof parsed === "object" && "message" in parsed) {
const m = (parsed as { message?: unknown }).message;
if (typeof m === "string" && m) return m;
}
} catch {
/* 非 JSON,按原文处理 */
}
return raw;
}