chore: error handler in stream response

This commit is contained in:
jialin
2025-04-30 12:26:37 +08:00
parent a3501e5417
commit fe52238ac2
+17 -4
View File
@@ -20,10 +20,25 @@ interface RequestConfig {
contentType?: 'json' | 'text'; contentType?: 'json' | 'text';
} }
async function parseErrorResponse(response: Response) {
try {
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
return await response.json();
} else {
const text = await response.text();
return { message: text || 'Unknown error' };
}
} catch (e) {
return { message: 'Failed to parse error response' };
}
}
const useSetChunkFetch = () => { const useSetChunkFetch = () => {
const axiosToken = useRef<any>(null); const axiosToken = useRef<any>(null);
const requestConfig = useRef<any>({}); const requestConfig = useRef<any>({});
const chunkDataRef = useRef<any>([]); const chunkDataRef = useRef<any>([]);
const readTextEventStreamData = async ( const readTextEventStreamData = async (
response: Response, response: Response,
callback: HandlerFunction, callback: HandlerFunction,
@@ -103,7 +118,7 @@ const useSetChunkFetch = () => {
bufferManager.add(chunk); bufferManager.add(chunk);
throttledCallback(); throttledCallback();
} catch (error) { } catch (error) {
console.log('error============:', error); // handle error
} }
} }
}; };
@@ -134,7 +149,7 @@ const useSetChunkFetch = () => {
); );
if (!response.ok) { if (!response.ok) {
const error = await response.json(); const error = await parseErrorResponse(response);
if (errorHandler) { if (errorHandler) {
errorHandler(error); errorHandler(error);
} else { } else {
@@ -144,8 +159,6 @@ const useSetChunkFetch = () => {
} }
await readTextEventStreamData(response, handler); await readTextEventStreamData(response, handler);
console.log('chunkDataRef.current===1', chunkDataRef.current);
} catch (error) { } catch (error) {
// handle error: catched in request interceptor // handle error: catched in request interceptor
} }