Skip to content

Commit

Permalink
fix(client): correctly handle errors during streaming (#377)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot authored Oct 13, 2023
1 parent a06c685 commit 09233b1
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/streaming.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { ReadableStream, type Response } from './_shims/index';
import { OpenAIError } from './error';

import { APIError } from 'openai/error';

type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;

type ServerSentEvent = {
Expand Down Expand Up @@ -58,13 +60,21 @@ export class Stream<Item> implements AsyncIterable<Item> {
}

if (sse.event === null) {
let data;

try {
yield JSON.parse(sse.data);
data = JSON.parse(sse.data);
} catch (e) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e;
}

if (data && data.error) {
throw new APIError(undefined, data.error, undefined, undefined);
}

yield data;
}
}
done = true;
Expand Down

0 comments on commit 09233b1

Please sign in to comment.