最近用了@microsoft/fetch-event-source库来处理sse流式请求,发现正常情况下是挺好用的,但遇到了错误返回的时候无法捕捉

情况1: 请求报500,控制台中无可预览的内容
修复1: 原因是headers中需要加上Accept: “/”,因为该库默认headers的Accept默认为"text/event-stream",遇到错误以后就会报500,捕获不到请求体,加上以后请求头会变成Accept: “/,text/event-stream”,这时控制台中已经可以捕获错误信息

情况2: 控制台中可以看到错误后的响应,但是打印请求数据后找不到返回的响应体
修复2: 在onopen: async (response) => {获取
onopen: async (response) => {
if (response.ok) {
const contentType = response.headers.get("content-type");
// 判断响应体是否为流式
if (!contentType?.startsWith("text/event-stream")) {
// 使用.json获取
const errorData = await response.json();
// 捕获的响应体
if (errorData.code === 202 && !errorData.success) {
//可做错误处理
}
}
}
},
全部代码
createCustomFetchEventSource({
url: apiUrl,
method: "POST",
headers: {
"Content-Type": "application/json;charset=UTF-8",
"X-DashScope-SSE": "enable",
Accept: "*/*",
Token: token,
},
body: JSON.stringify(dataPayload),
signal: controller.signal,
onopen: async (response) => {
if (response.ok) {
const contentType = response.headers.get("content-type");
// 判断响应体是否为流式
if (!contentType?.startsWith("text/event-stream")) {
// 使用.json获取
const errorData = await response.json();
// 捕获的响应体
if (errorData.code === 202 && !errorData.success) {
//可做错误处理
}
}
}
},
onmessage: (event) => {
},
onclose: () => {
console.log("onclose");
},
onerror: (error) => {
console.error("SSE Error:", error);
},
});
} catch (error) {
console.error("Error sending message to AI:", error);
}