"use client"; import { toast } from "sonner"; import { ApiClientError } from "@/services/api-client"; interface ShowApiErrorOptions { /** * Used as the toast title when the error has no actionable code (e.g. a * raw `Error` from a non-API path). Ignored for `ApiClientError`, which * always shows `[CODE] message` so codes stay grep-able. */ fallbackTitle?: string; } /** * Standard error toast for any API failure. * * - `ApiClientError`: title is `[upstreamCode || code] message` so the user * sees `[SignatureDoesNotMatch]` instead of just "Access denied", and * the diagnostic context (trace id, upstream request id) lands in the * description for support attachments. * - Other errors: title is `fallbackTitle` if provided, otherwise the * error's `message`. */ export function showApiError( error: unknown, options: ShowApiErrorOptions = {}, ): void { if (error instanceof ApiClientError) { const description = formatErrorContext(error); if (description) { toast.error(error.displayMessage, { description }); } else { toast.error(error.displayMessage); } return; } const message = error instanceof Error ? error.message : String(error ?? "未知错误"); if (options.fallbackTitle) { if (message) { toast.error(options.fallbackTitle, { description: message }); } else { toast.error(options.fallbackTitle); } return; } toast.error(message); } /** * Compact one-line context block shown beneath the main error message * (toast description or EmptyState subtitle). Each part is short enough * that the line stays readable but informative enough for a support agent * to find the corresponding log entry. */ export function formatErrorContext(error: ApiClientError): string { const parts: string[] = []; const upstreamReq = error.details?.upstreamRequestId; if (upstreamReq) parts.push(`OSS RequestId: ${upstreamReq}`); if (error.traceId) parts.push(`Trace: ${shortId(error.traceId)}`); if (error.requestId && error.requestId !== upstreamReq) { parts.push(`Req: ${shortId(error.requestId)}`); } return parts.join(" · "); } function shortId(id: string): string { return id.length > 8 ? `${id.slice(0, 8)}…` : id; }