Skip to content

Commit

Permalink
Fix unhandled rejections with edge runtime (#39091)
Browse files Browse the repository at this point in the history
This corrects some unhandledRejection errors showing when a connection is canceled with the edge runtime since the changes needed for 14463dd. This also adds a regression test to ensure we don't have these class of errors in our middleware tests. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Fixes: [slack thread](https://vercel.slack.com/archives/C03Q1UU3Z4H/p1658960102013969)
  • Loading branch information
ijjk committed Jul 28, 2022
1 parent c4d4125 commit f1aac90
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
16 changes: 12 additions & 4 deletions packages/next/server/body-streams.ts
Expand Up @@ -56,9 +56,13 @@ export function getClonableBody<T extends IncomingMessage>(
): ClonableBody {
let buffered: Readable | null = null

const endPromise = new Promise((resolve, reject) => {
readable.on('end', resolve)
readable.on('error', reject)
const endPromise = new Promise<void | { error?: unknown }>(
(resolve, reject) => {
readable.on('end', resolve)
readable.on('error', reject)
}
).catch((error) => {
return { error }
})

return {
Expand All @@ -69,7 +73,11 @@ export function getClonableBody<T extends IncomingMessage>(
*/
async finalize(): Promise<void> {
if (buffered) {
await endPromise
const res = await endPromise

if (res && typeof res === 'object' && res.error) {
throw res.error
}
replaceRequestBody(readable, buffered)
buffered = readable
}
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/middleware-rewrites/test/index.test.ts
Expand Up @@ -680,6 +680,11 @@ describe('Middleware Rewrite', () => {
logs.every((log) => log.source === 'log' || log.source === 'info')
).toEqual(true)
})

it('should not have unexpected errors', async () => {
expect(next.cliOutput).not.toContain('unhandledRejection')
expect(next.cliOutput).not.toContain('ECONNRESET')
})
}

function getCookieFromResponse(res, cookieName) {
Expand Down

0 comments on commit f1aac90

Please sign in to comment.