Skip to content

Commit 1950ba3

Browse files
authored
Properly handle event source errors (#687)
* Properly handle event source errors * Changeset * Fix TS
1 parent 827b288 commit 1950ba3

File tree

4 files changed

+19
-6
lines changed

4 files changed

+19
-6
lines changed

.changeset/heavy-olives-divide.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@gitbook/api': patch
3+
---
4+
5+
Improve error handling for streamed API operations.

bun.lockb

0 Bytes
Binary file not shown.

packages/api/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
],
1414
"dependencies": {
1515
"event-iterator": "^2.0.0",
16-
"eventsource-parser": "^1.1.1"
16+
"eventsource-parser": "^3.0.0"
1717
},
1818
"devDependencies": {
1919
"swagger-typescript-api": "^13.0.3",

packages/api/templates/http-client.ejs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
const { apiConfig, generateResponses, config } = it;
33
%>
44
import { EventIterator } from 'event-iterator';
5-
import { createParser, type ParsedEvent, type ReconnectInterval } from 'eventsource-parser';
5+
import { createParser, type EventSourceMessage } from 'eventsource-parser';
66

77
export type QueryParamsType = Record<string | number, any>;
88
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
@@ -277,15 +277,23 @@ export class HttpClient<SecurityDataType = unknown> {
277277
queue.stop();
278278
}
279279

280-
const parser = createParser((event: ParsedEvent | ReconnectInterval) => {
281-
if (event.type === 'event') {
282-
if (event.data === 'done') {
280+
const parser = createParser({
281+
onEvent: (event: EventSourceMessage) => {
282+
if (event.event === 'done') {
283283
stop();
284+
} else if (event.event === 'error') {
285+
const data = JSON.parse(event.data);
286+
reader.cancel();
287+
queue.fail(new Error(data.error.message));
284288
} else {
285289
const data = JSON.parse(event.data);
286290
queue.push(data);
287291
}
288-
}
292+
},
293+
onError: (error) => {
294+
reader.cancel();
295+
queue.fail(error);
296+
},
289297
})
290298

291299
const decoder = new TextDecoder();

0 commit comments

Comments
 (0)