diff --git a/src/helper/streaming/stream.test.ts b/src/helper/streaming/stream.test.ts index 820579de5..4a9eff2ed 100644 --- a/src/helper/streaming/stream.test.ts +++ b/src/helper/streaming/stream.test.ts @@ -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( diff --git a/src/helper/streaming/stream.ts b/src/helper/streaming/stream.ts index 3d0449573..5878c2188 100644 --- a/src/helper/streaming/stream.ts +++ b/src/helper/streaming/stream.ts @@ -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)