Unverified Commit c5dab314 authored by Josh Story's avatar Josh Story Committed by GitHub

Ignore unhandledRejection events for promises that reject after a React render aborts (#83590)

Currently we only abort React renders that are prerendered so this
change in practice only affects prerendering. The intent is to not
report unhandledRejections that are downstream of an abort because the
signal these errors provide is very limited. If you do have unrelated
unhandled rejections they'll usually show up before aborting or in a
dynamic page render so even if they are incidentally supressed in the
prerender context you should still be able to observe them.

Arguably we should go further and never report unhandled rejections
because there are still valid patterns where you initiate work
prospectively and then abandon it by choosing a fork or by returning
early (i.e. notFound()). This change doesn't attempt to cover every
possible case.

The implementation is a bit intense. We need the ability to stop
propagating the event which is not natively supported with Node's
EventEmitter interface. Instead we patch the listener methods to
delegate the filtering to an inner listener queue. If you add/remove or
otherwise manipulate the listener list we always ensure our listener is
first and can opt to omit propagating the event. If you want to
uninstall the this patch you just need to unregister this listener
specifically which can be accessing used
`process.listeners('unhandledRejection')[0]`

This patch only exists for the node environment because we do not do any
prerendering in edge runtimes. In the future if we add aborting to
environments like edge runtime we may need an alternative solution to
this problem
parent bc3ab447
...@@ -5,6 +5,7 @@ import './node-environment-baseline' ...@@ -5,6 +5,7 @@ import './node-environment-baseline'
// Import as early as possible so that unexpected errors in other extensions are properly formatted. // Import as early as possible so that unexpected errors in other extensions are properly formatted.
// Has to come after baseline since error-inspect requires AsyncLocalStorage that baseline provides. // Has to come after baseline since error-inspect requires AsyncLocalStorage that baseline provides.
import './node-environment-extensions/error-inspect' import './node-environment-extensions/error-inspect'
import './node-environment-extensions/unhandled-rejection'
import './node-environment-extensions/random' import './node-environment-extensions/random'
import './node-environment-extensions/date' import './node-environment-extensions/date'
import './node-environment-extensions/web-crypto' import './node-environment-extensions/web-crypto'
......
...@@ -5074,5 +5074,90 @@ describe('Cache Components Errors', () => { ...@@ -5074,5 +5074,90 @@ describe('Cache Components Errors', () => {
}) })
} }
}) })
describe('Unhandled Rejection Suppression', () => {
const pathname = '/unhandled-rejection'
if (isNextDev) {
it('should suppress unhandled rejections during prerender validation in dev', async () => {
const browser = await next.browser(pathname)
await expect(browser).toDisplayCollapsedRedbox(`
[
{
"description": "BOOM",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": null,
"stack": [
"Page <anonymous>",
],
},
{
"description": " ⨯ "unhandledRejection:" "BOOM"",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": null,
"stack": [
"Page <anonymous>",
],
},
{
"description": " ⨯ "unhandledRejection: " "BOOM"",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": null,
"stack": [
"Page <anonymous>",
],
},
{
"description": "BAM",
"environmentLabel": "Server",
"label": "Console Error",
"source": null,
"stack": [
"Page <anonymous>",
],
},
{
"description": " ⨯ "unhandledRejection:" "BAM"",
"environmentLabel": "Server",
"label": "Console Error",
"source": null,
"stack": [
"Page <anonymous>",
],
},
{
"description": " ⨯ "unhandledRejection: " "BAM"",
"environmentLabel": "Server",
"label": "Console Error",
"source": null,
"stack": [
"Page <anonymous>",
],
},
]
`)
})
} else {
it('should suppress unhandled rejections after prerender abort', async () => {
try {
await prerender(pathname)
} catch {}
const output = getPrerenderOutput(
next.cliOutput.slice(cliOutputLength),
{ isMinified: !isDebugPrerender }
)
expect(output).toMatchInlineSnapshot(`
"BOOM
BOOM"
`)
})
}
})
}) })
}) })
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>
<Suspense>{children}</Suspense>
</main>
</body>
</html>
)
}
export default async function Page() {
// This promise will reject before we abort during prerendering
Promise.reject('BOOM')
// This promise will reject after we abort during prerendering
setTimeout(() => {
Promise.reject('BAM')
}, 0)
return (
<>
<p>
This page tests unhandled rejection suppression after prerender abort.
</p>
<p>
With cache components enabled, this page produces a partial static shell
and it has one early rejection "BOOM" which will show up but two late
rejections which should not
</p>
</>
)
}
// Used to deterministically stub out minified local names in stack traces. // Used to deterministically stub out minified local names in stack traces.
const abc = 'abcdefghijklmnopqrstuvwxyz' const abc = 'abcdefghijklmnopqrstuvwxyz'
const hostElementsUsedInFixtures = ['html', 'body', 'main', 'div'] const hostElementsUsedInFixtures = ['html', 'body', 'main', 'div']
const ignoredLines = ['Generating static pages', 'Inlining static env'] const ignoredLines = [
'Generating static pages',
'Inlining static env',
'Finalizing page optimization',
]
/** /**
* Converts a module function sequence expression, e.g.: * Converts a module function sequence expression, e.g.:
...@@ -50,6 +54,10 @@ export function getPrerenderOutput( ...@@ -50,6 +54,10 @@ export function getPrerenderOutput(
break break
} }
if (line.includes('Route (app)')) {
break
}
if ( if (
foundPrerenderingLine && foundPrerenderingLine &&
!ignoredLines.some((ignoredLine) => line.includes(ignoredLine)) !ignoredLines.some((ignoredLine) => line.includes(ignoredLine))
......
...@@ -5,16 +5,12 @@ export default async function Page(props: { ...@@ -5,16 +5,12 @@ export default async function Page(props: {
params: Promise<{}> params: Promise<{}>
searchParams: Promise<{}> searchParams: Promise<{}>
}) { }) {
setTimeout(async () => await props.params) props.params.catch(logReason)
setTimeout(async () => await props.searchParams) props.searchParams.catch(logReason)
let pendingCookies = cookies() cookies().catch(logReason)
setTimeout(async () => await pendingCookies) headers().catch(logReason)
let pendingHeaders = headers() draftMode().catch(logReason)
setTimeout(async () => await pendingHeaders) connection().catch(logReason)
let pendingDraftMode = draftMode()
setTimeout(async () => await pendingDraftMode)
let pendingConnection = connection()
setTimeout(async () => await pendingConnection)
return ( return (
<> <>
<p> <p>
...@@ -31,6 +27,10 @@ export default async function Page(props: { ...@@ -31,6 +27,10 @@ export default async function Page(props: {
) )
} }
function logReason(reason: any) {
console.log('Reason:', reason)
}
async function TriggerSyncDynamic() { async function TriggerSyncDynamic() {
await new Promise((r) => process.nextTick(r)) await new Promise((r) => process.nextTick(r))
return Math.random() return Math.random()
......
...@@ -5,16 +5,12 @@ export default async function Page(props: { ...@@ -5,16 +5,12 @@ export default async function Page(props: {
params: Promise<{}> params: Promise<{}>
searchParams: Promise<{}> searchParams: Promise<{}>
}) { }) {
setTimeout(async () => await props.params) props.params.catch(logReason)
setTimeout(async () => await props.searchParams) props.searchParams.catch(logReason)
let pendingCookies = cookies() cookies().catch(logReason)
setTimeout(async () => await pendingCookies) headers().catch(logReason)
let pendingHeaders = headers() draftMode().catch(logReason)
setTimeout(async () => await pendingHeaders) connection().catch(logReason)
let pendingDraftMode = draftMode()
setTimeout(async () => await pendingDraftMode)
let pendingConnection = connection()
setTimeout(async () => await pendingConnection)
return ( return (
<> <>
<p> <p>
...@@ -26,3 +22,7 @@ export default async function Page(props: { ...@@ -26,3 +22,7 @@ export default async function Page(props: {
</> </>
) )
} }
function logReason(reason: any) {
console.log('Reason:', reason)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment