From ec046b7095eab4c5455ef9a1c036364b76f650f0 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 16 Oct 2023 10:13:13 +0000 Subject: [PATCH] fix(client): correctly handle errors during streaming --- src/streaming.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/streaming.ts b/src/streaming.ts index f69724d64..33f641888 100644 --- a/src/streaming.ts +++ b/src/streaming.ts @@ -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 = { @@ -58,13 +60,21 @@ export class Stream implements AsyncIterable { } 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;