Skip to content

Commit 8267021

Browse files
committed
fix(sse): refine error reporting
1 parent 96c20c7 commit 8267021

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed

packages/utils/src/general/createSSEStream.spec.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,53 @@ describe("createSSEStream", () => {
139139
expect(consoleError).toHaveBeenCalledWith("open error", "Internal Error");
140140
});
141141

142+
test("open error with json error", async () => {
143+
mockFetchEventSource.mockImplementation(async (_url, options) => {
144+
const { onopen, onerror } = options;
145+
await Promise.resolve();
146+
try {
147+
await onopen?.({
148+
ok: false,
149+
statusText: "Internal Error",
150+
text: () =>
151+
Promise.resolve(
152+
JSON.stringify({
153+
error: "Something went wrong",
154+
})
155+
),
156+
} as Response);
157+
} catch (e) {
158+
await onerror?.(e);
159+
}
160+
});
161+
await expect(createSSEStream(url)).rejects.toMatchInlineSnapshot(
162+
`[Error: Something went wrong]`
163+
);
164+
expect(consoleError).toHaveBeenCalledTimes(1);
165+
expect(consoleError).toHaveBeenCalledWith("open error", "Internal Error");
166+
});
167+
168+
test("open error with non-json error", async () => {
169+
mockFetchEventSource.mockImplementation(async (_url, options) => {
170+
const { onopen, onerror } = options;
171+
await Promise.resolve();
172+
try {
173+
await onopen?.({
174+
ok: false,
175+
statusText: "Internal Error",
176+
text: () => Promise.resolve("Oops"),
177+
} as Response);
178+
} catch (e) {
179+
await onerror?.(e);
180+
}
181+
});
182+
await expect(createSSEStream(url)).rejects.toMatchInlineSnapshot(
183+
`[Error: Oops]`
184+
);
185+
expect(consoleError).toHaveBeenCalledTimes(1);
186+
expect(consoleError).toHaveBeenCalledWith("open error", "Internal Error");
187+
});
188+
142189
test("message error", async () => {
143190
mockFetchEventSource.mockImplementation(async (_url, options) => {
144191
const { onopen, onmessage } = options;

packages/utils/src/general/createSSEStream.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,24 @@ export async function createSSEStream<T = unknown>(
6262
} else {
6363
// eslint-disable-next-line no-console
6464
console.error("open error", response.statusText);
65-
throw new Error(response.statusText);
65+
let text: string;
66+
try {
67+
text = await response.text();
68+
} catch {
69+
throw new Error(response.statusText);
70+
}
71+
72+
let json: any;
73+
try {
74+
json = JSON.parse(text);
75+
} catch {
76+
// Do nothing
77+
}
78+
79+
if (typeof json?.error === "string") {
80+
throw new Error(json.error);
81+
}
82+
throw new Error(text);
6683
}
6784
},
6885
onmessage(msg) {

0 commit comments

Comments
 (0)