Hide goose from user-facing connection errors

This commit is contained in:
john
2026-06-25 23:44:58 +08:00
parent e133f9a3a4
commit d51df2fb0a
2 changed files with 77 additions and 14 deletions
+27 -7
View File
@@ -60,7 +60,7 @@ export class ApiError extends Error {
code?: string,
details?: InsufficientBalanceDetails | Record<string, unknown>,
) {
super(message);
super(sanitizeUserFacingErrorMessage(message));
this.name = 'ApiError';
this.status = status;
this.code = code;
@@ -68,6 +68,21 @@ export class ApiError extends Error {
}
}
function sanitizeUserFacingErrorMessage(message: string) {
const normalized = String(message ?? '').trim();
if (!normalized) return normalized;
if (!/goose|goosed/i.test(normalized)) return normalized;
if (/超时|timeout/i.test(normalized)) {
return '后端连接超时,请确认后端服务正常后重试';
}
if (/不可用|连接失败|failed to fetch|networkerror|fetch failed|upstream|econn|enotfound/i.test(normalized)) {
return '后端连接失败,请稍后重试';
}
return normalized
.replace(/\bgoosed\b/gi, '后端服务')
.replace(/\bgoose\b/gi, '后端');
}
async function parseErrorResponse(res: Response): Promise<{
message: string;
code?: string;
@@ -95,7 +110,7 @@ async function parseErrorResponse(res: Response): Promise<{
const details = nested.details ?? body.details;
if (code === 'INSUFFICIENT_BALANCE') {
return {
message,
message: sanitizeUserFacingErrorMessage(message),
code,
details: {
code: 'INSUFFICIENT_BALANCE' as const,
@@ -112,14 +127,14 @@ async function parseErrorResponse(res: Response): Promise<{
};
}
return {
message,
message: sanitizeUserFacingErrorMessage(message),
code,
details: details && typeof details === 'object'
? (details as InsufficientBalanceDetails | Record<string, unknown>)
: undefined,
};
} catch {
return { message: text || res.statusText };
return { message: sanitizeUserFacingErrorMessage(text || res.statusText) };
}
}
@@ -200,12 +215,17 @@ async function portalFetch<T>(path: string, init?: RequestInit): Promise<T> {
function formatNetworkError(err: unknown) {
const message = err instanceof Error ? err.message : '网络请求失败';
if (err instanceof DOMException && err.name === 'AbortError') {
return '连接 goose 服务超时,请确认 goosed/H5 后端正在运行后重试';
return '后端连接超时,请确认后端服务正常后重试';
}
if (message.includes('Failed to fetch') || message.includes('NetworkError')) {
return '无法连接后端服务,请先运行: pnpm dev 或 node server.mjs';
}
return message;
return sanitizeUserFacingErrorMessage(message);
}
function sanitizeSessionEvent(event: SessionEvent): SessionEvent {
if (event.type !== 'Error') return event;
return { ...event, error: sanitizeUserFacingErrorMessage(event.error) };
}
async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
@@ -1921,7 +1941,7 @@ export function subscribeSessionEvents(
}
continue;
}
onEvent(JSON.parse(data) as SessionEvent);
onEvent(sanitizeSessionEvent(JSON.parse(data) as SessionEvent));
} catch {
// ignore malformed frames
}