36 行
1011 B
TypeScript
36 行
1011 B
TypeScript
import { isApiError } from "../api/types";
|
||
import { mapApiErrorMessage } from "../api/errorMessages";
|
||
|
||
function toUserSafeMessage(message: string | undefined, fallback: string) {
|
||
const normalized = (message ?? "")
|
||
.trim()
|
||
.replace(/^(?:[A-Z][A-Z0-9_]{2,}|\d{3})[::]\s*/, "");
|
||
if (!normalized) {
|
||
return fallback;
|
||
}
|
||
|
||
const exposesTechnicalDetail =
|
||
!/[\u3400-\u9fff]/.test(normalized) ||
|
||
/https?:\/\/|\/api\/|(?:^|\s)\/[A-Za-z0-9._-]+(?:\/[^\s]*)?|[A-Za-z]:\\|(?:^|\n)\s*at\s|\b(?:GET|POST|PUT|PATCH|DELETE)\s+\/|^(?:\{|\[)/.test(normalized);
|
||
|
||
return exposesTechnicalDetail ? fallback : normalized;
|
||
}
|
||
|
||
export function resolveErrorMessage(
|
||
error: unknown,
|
||
fallback = "操作失败,请稍后重试",
|
||
): string {
|
||
if (isApiError(error)) {
|
||
return toUserSafeMessage(
|
||
mapApiErrorMessage(error.code, error.details, error.message),
|
||
fallback,
|
||
);
|
||
}
|
||
|
||
if (error instanceof Error) {
|
||
return toUserSafeMessage(error.message, fallback);
|
||
}
|
||
|
||
return fallback;
|
||
}
|