Skip to content

Commit c0c2e71

Browse files
Merge pull request transitive-bullshit#431 from sighingnow/fix-error-handling
2 parents 6c309ce + 452a61e commit c0c2e71

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

src/chatgpt-unofficial-proxy-api.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,8 +219,11 @@ export class ChatGPTUnofficialProxyAPI {
219219
}
220220
} catch (err) {
221221
// ignore for now; there seem to be some non-json messages
222-
// console.warn('fetchSSE onMessage unexpected error', err)
222+
reject(err)
223223
}
224+
},
225+
onError: (err) => {
226+
reject(err)
224227
}
225228
},
226229
this._fetch

src/fetch-sse.ts

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,13 @@ import { streamAsyncIterable } from './stream-async-iterable'
66

77
export async function fetchSSE(
88
url: string,
9-
options: Parameters<typeof fetch>[1] & { onMessage: (data: string) => void },
9+
options: Parameters<typeof fetch>[1] & {
10+
onMessage: (data: string) => void
11+
onError?: (error: any) => void
12+
},
1013
fetch: types.FetchFn = globalFetch
1114
) {
12-
const { onMessage, ...fetchOptions } = options
15+
const { onMessage, onError, ...fetchOptions } = options
1316
const res = await fetch(url, fetchOptions)
1417
if (!res.ok) {
1518
let reason: string
@@ -33,6 +36,31 @@ export async function fetchSSE(
3336
}
3437
})
3538

39+
// check if the response is an error, if so, throw it
40+
const feed = (chunk: string) => {
41+
let response = null
42+
try {
43+
response = JSON.parse(chunk)
44+
} catch {
45+
/// ignore
46+
}
47+
if (response?.detail) {
48+
if (response.detail.type === 'invalid_request_error') {
49+
const msg = `ChatGPT error ${response.detail.message}: ${response.detail.code} (${response.detail.type})`
50+
const error = new types.ChatGPTError(msg, { cause: response })
51+
error.statusCode = response.detail.code
52+
error.statusText = response.detail.message
53+
if (onError) {
54+
onError(error)
55+
} else {
56+
console.error(error)
57+
}
58+
return // don't feed to event parser
59+
}
60+
}
61+
parser.feed(chunk)
62+
}
63+
3664
if (!res.body.getReader) {
3765
// Vercel polyfills `fetch` with `node-fetch`, which doesn't conform to
3866
// web standards, so this is a workaround...
@@ -45,13 +73,13 @@ export async function fetchSSE(
4573
body.on('readable', () => {
4674
let chunk: string | Buffer
4775
while (null !== (chunk = body.read())) {
48-
parser.feed(chunk.toString())
76+
feed(chunk.toString())
4977
}
5078
})
5179
} else {
5280
for await (const chunk of streamAsyncIterable(res.body)) {
5381
const str = new TextDecoder().decode(chunk)
54-
parser.feed(str)
82+
feed(str)
5583
}
5684
}
5785
}

0 commit comments

Comments
 (0)