From 8c049c9ee9b99e294186ad0c8836616dc67fe2e3 Mon Sep 17 00:00:00 2001 From: heimoshuiyu Date: Mon, 3 Apr 2023 17:39:43 +0800 Subject: [PATCH] handle response error --- src/chatgpt.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/chatgpt.ts b/src/chatgpt.ts index 32fca12..b6d120b 100644 --- a/src/chatgpt.ts +++ b/src/chatgpt.ts @@ -11,6 +11,7 @@ export interface ChunkMessage { } export interface FetchResponse { + error?: any; id: string; object: string; created: number; @@ -88,7 +89,11 @@ class Chat { async fetch(): Promise { const resp = await this._fetch(); - return await resp.json(); + const j = await resp.json(); + if (j.error !== undefined) { + throw JSON.stringify(j.error); + } + return j; } async say(content: string): Promise { @@ -98,6 +103,9 @@ class Chat { } processFetchResponse(resp: FetchResponse): string { + if (resp.error !== undefined) { + throw JSON.stringify(resp.error); + } this.total_tokens = resp?.usage?.total_tokens ?? 0; if (resp?.choices[0]?.message) { this.messages.push(resp?.choices[0]?.message);