fix(chat): 将流式错误信息映射为面向用户的提示方案

This commit is contained in:
sophie committed 2026-06-19 21:25:14 +08:00
1 parent 6757ad869f
commit 10b6f9b692
8 files changed
+127 -2

No files matched your search

@@ -0,0 +1,88 @@
/**
* features/chat/utils/streamErrorMessage.ts
* 用途:将 SSE / 浏览器流式读错映射为用户可读文案。
* 依赖:vue-i18n chat.streamError 词条。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage。
*/
import type { ChatMessage } from '../types/chat.types';
const NETWORK_DISCONNECT_PATTERNS = [
'network error',
'failed to fetch',
'load failed',
'networkerror when attempting to fetch resource',
'network issue',
];
const UPSTREAM_DISCONNECT_PATTERNS = [
'response ended prematurely',
'chunkedencodingerror',
];
export interface StreamErrorLabels {
networkDisconnectedEmpty: string;
partialInterrupted: string;
upstreamDisconnected: string;
generic: string;
}
/**
* 判断是否为浏览器侧 SSE / fetch 连接中断类错误。
*/
export function isNetworkDisconnectError(message: string): boolean {
const normalized = message.trim().toLowerCase();
if (!normalized) return false;
return NETWORK_DISCONNECT_PATTERNS.some(
(pattern) => normalized === pattern || normalized.includes(pattern),
);
}
/**
* 判断是否为上游(Dify)流式响应提前结束。
*/
export function isUpstreamDisconnectError(message: string): boolean {
const normalized = message.trim().toLowerCase();
return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern));
}
/**
* 将原始错误信息映射为面向用户的提示文案。
*
* @param rawMessage - 浏览器或后端返回的原始错误
* @param hasContent - 是否已有部分回答内容
* @param labels - i18n 文案集合
*/
export function resolveStreamErrorText(
rawMessage: string,
hasContent: boolean,
labels: StreamErrorLabels,
): string {
if (isNetworkDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty;
}
if (isUpstreamDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected;
}
if (/[\u4e00-\u9fff]/.test(rawMessage)) {
return rawMessage;
}
return labels.generic;
}
/**
* 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。
*/
export function applyStreamErrorToMessage(
msg: ChatMessage,
rawMessage: string,
labels: StreamErrorLabels,
): void {
const hasContent = Boolean(msg.content.trim());
const text = resolveStreamErrorText(rawMessage, hasContent, labels);
msg.stream_error = true;
if (hasContent) {
msg.content += `\n\n${text}`;
} else {
msg.content = text;
}
}
@@ -41,6 +41,7 @@ export function resolveMessageAnchorKey(msg: ChatMessage, index: number): string
}
export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean {
if (msg?.stream_error) return true;
return String(msg?.content || '').includes('[Error:');
}