Commit 10a746a8 by Liu

fix:打印

parent ca97a942
...@@ -24,16 +24,22 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe ...@@ -24,16 +24,22 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe
buffer = lines.pop() as string buffer = lines.pop() as string
lines.forEach((line) => { lines.forEach((line) => {
if (line === '') { // 读取到空行,一个数据块发送完成 if (line === '') { // 读取到空行,一个数据块发送完成
onMessage({ try {
type: 'DATA', onMessage({
content: JSON.parse(dataMsgBuffer), type: 'DATA',
}) content: JSON.parse(dataMsgBuffer),
})
}
catch {
// 解析失败时静默处理,避免报错
}
dataMsgBuffer = '' dataMsgBuffer = ''
return return
} }
const [type] = line.split(':', 1) const [type] = line.split(':', 1)
const content = line.substring(type.length + 1) const content = line.substring(type.length + 1)
if (type === 'data') { // 数据块没有收到空行之前放入buffer中 if (type === 'data') { // 数据块没有收到空行之前放入buffer中
// SSE 格式中,data: 后面的内容前面可能有一个空格,trim 可以安全处理
dataMsgBuffer += content.trim() dataMsgBuffer += content.trim()
} }
else if (type === '' && content !== '') { // 服务端发送的注释,用于保证链接不断开 else if (type === '' && content !== '') { // 服务端发送的注释,用于保证链接不断开
...@@ -57,9 +63,9 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe ...@@ -57,9 +63,9 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe
type: 'END', type: 'END',
}) })
} }
}).catch((error) => { }).catch((error: unknown) => {
// 如果是 AbortError,不发送错误消息 // 如果是 AbortError,不发送错误消息
if (error.name === 'AbortError') { if (error instanceof Error && error.name === 'AbortError') {
return return
} }
onMessage({ onMessage({
...@@ -93,9 +99,9 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe ...@@ -93,9 +99,9 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe
.then((reader) => { .then((reader) => {
return processMessage(reader) return processMessage(reader)
}) })
.catch((error) => { .catch((error: unknown) => {
// 如果是 AbortError,不发送错误消息 // 如果是 AbortError,不发送错误消息
if (error.name === 'AbortError') { if (error instanceof Error && error.name === 'AbortError') {
return return
} }
onMessage({ onMessage({
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment