Skip to content

Commit

Permalink
fix(streaming) Prevent console.error(undefined) (#3747)
Browse files Browse the repository at this point in the history
  • Loading branch information
aantthony authored Dec 14, 2024
1 parent baa231e commit dffd60f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/helper/streaming/stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ describe('Basic Streaming Helper', () => {
expect(aborted).toBeTruthy()
})

it('Check stream Response if pipe is aborted by abort signal', async () => {
const ac = new AbortController()
const req = new Request('http://localhost/', { signal: ac.signal })
const c = new Context(req)

let aborted = false
const res = stream(c, async (stream) => {
stream.onAbort(() => {
aborted = true
})
await stream.pipe(new ReadableStream())
})
if (!res.body) {
throw new Error('Body is null')
}
const reader = res.body.getReader()
const pReading = reader.read()
ac.abort()
await pReading
expect(aborted).toBeTruthy()
})

it('Check stream Response if error occurred', async () => {
const onError = vi.fn()
const res = stream(
Expand Down
6 changes: 5 additions & 1 deletion src/helper/streaming/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export const stream = (
try {
await cb(stream)
} catch (e) {
if (e instanceof Error && onError) {
if (e === undefined) {
// If reading is canceled without a reason value (e.g. by StreamingApi)
// then the .pipeTo() promise will reject with undefined.
// In this case, do nothing because the stream is already closed.
} else if (e instanceof Error && onError) {
await onError(e, stream)
} else {
console.error(e)
Expand Down

0 comments on commit dffd60f

Please sign in to comment.