Skip to content

Commit 872ab97

Browse files
authored
Merge pull request #1768 from GavanHub/fix/sse-error-handling
fix: SSE请求增加HTTP错误处理及401自动跳转登录
2 parents 9f15cac + b418836 commit 872ab97

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

web/app/src/components/QaModal/AiQaContent.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { postShareV1ChatFeedback } from '@/request/ShareChat';
1111
import { getShareV1ConversationDetail } from '@/request/ShareConversation';
1212
import { postShareV1CommonFileUpload } from '@/request/ShareFile';
1313
import { copyText } from '@/utils';
14-
import SSEClient from '@/utils/fetch';
14+
import SSEClient, { SSEHttpError } from '@/utils/fetch';
1515
import { Image as ImagePreview, message } from '@ctzhian/ui';
1616
import CloseIcon from '@mui/icons-material/Close';
1717
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
@@ -615,6 +615,16 @@ const AiQaContent: React.FC<{
615615
headers: {
616616
'Content-Type': 'application/json',
617617
},
618+
onError: error => {
619+
setLoading(false);
620+
setThinking(4);
621+
if (error instanceof SSEHttpError && error.status === 401) {
622+
const current = window.location;
623+
window.location.href = `${basePath}/auth/login?redirect=${encodeURIComponent(current.pathname + current.search)}`;
624+
return;
625+
}
626+
message.error(error.message || '请求失败');
627+
},
618628
onCancel: () => {
619629
setLoading(false);
620630
setThinking(4);

web/app/src/utils/fetch.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,15 @@ type SSECallback<T> = (data: T) => void;
22
type SSEErrorCallback = (error: Error) => void;
33
type SSECompleteCallback = () => void;
44

5+
export class SSEHttpError extends Error {
6+
status: number;
7+
constructor(status: number, message: string) {
8+
super(message);
9+
this.name = 'SSEHttpError';
10+
this.status = status;
11+
}
12+
}
13+
514
interface SSEClientOptions {
615
url: string;
716
headers?: Record<string, string>;
@@ -63,7 +72,13 @@ class SSEClient<T> {
6372
.then(async response => {
6473
if (!response.ok) {
6574
clearTimeout(timeoutId);
66-
throw new Error(`HTTP error! status: ${response.status}`);
75+
let errorMessage = `HTTP error! status: ${response.status}`;
76+
try {
77+
const body = await response.json();
78+
if (body?.message) errorMessage = body.message;
79+
else if (body?.error) errorMessage = body.error;
80+
} catch {}
81+
throw new SSEHttpError(response.status, errorMessage);
6782
}
6883
if (!response.body) {
6984
clearTimeout(timeoutId);

0 commit comments

Comments
 (0)