Unverified Commit 7612eaed authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Consolidate unhandled rejection logging into a single listener (#95999)

An unhandled rejection was previously logged by up to three independent
process listeners at once: the render runtime's crash-prevention handler
in `process-error-handlers.ts` (a bare `console.error`), the router
server's `Log.error('unhandledRejection: ', err)`, and the dev server's
`logErrorWithOriginalStack`. The runtime handler must exist on every
deployment target (#77997), but on self-hosted `next start`/`next dev`
it shares a process with the router server's and dev server's listeners,
so a single rejection was logged multiple times in different formats.

THe first commits adds a test showing the current behavior where we log
multiple times.

The second commit introduces `registerUnhandledRejectionListener` and
`isUnhandledRejectionListenerRegistered` in `process-error-handlers.ts`,
and converts the router server and dev server to check-then-register
instead of installing their own rejection loggers:

- The listener function is shared via a `Symbol.for` key on
`globalThis`, so multiple copies of the module (e.g. in the pre-compiled
server bundle and in a route module bundle) register and detect a single
listener instance.
- The registration check queries
`process.listeners('unhandledRejection')` instead of a module-global
flag, so it stays accurate even after external code calls
`process.removeAllListeners`. `installProcessErrorHandlers` therefore
calls the register function unconditionally.

The `uncaughtException` handlers are left as they are; they have the
same duplication and could be consolidated the same way in a follow-up.
parent 9bfaf63e
...@@ -73,7 +73,10 @@ import { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-r ...@@ -73,7 +73,10 @@ import { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-r
import { LRUCache } from '../lib/lru-cache' import { LRUCache } from '../lib/lru-cache'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
import { DetachedPromise } from '../../lib/detached-promise' import { DetachedPromise } from '../../lib/detached-promise'
import { isPostpone } from '../lib/router-utils/is-postpone' import {
isUnhandledRejectionListenerRegistered,
registerUnhandledRejectionListener,
} from '../node-environment-extensions/process-error-handlers'
import { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites' import { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'
import { buildCustomRoute } from '../../lib/build-custom-route' import { buildCustomRoute } from '../../lib/build-custom-route'
import { decorateServerError } from '../../shared/lib/error-source' import { decorateServerError } from '../../shared/lib/error-source'
...@@ -378,14 +381,14 @@ export default class DevServer extends Server { ...@@ -378,14 +381,14 @@ export default class DevServer extends Server {
setGlobal('telemetry', telemetry) setGlobal('telemetry', telemetry)
} }
process.on('unhandledRejection', (reason) => { // The router server or the render server may run in the same process and
if (isPostpone(reason)) { // have already registered the unhandled rejection listener, in which case
// React postpones that are unhandled might end up logged here but they're // we must not register another one, to avoid logging unhandled rejections
// not really errors. They're just part of rendering. // multiple times.
return if (!isUnhandledRejectionListenerRegistered()) {
} registerUnhandledRejectionListener()
this.logErrorWithOriginalStack(reason, 'unhandledRejection') }
})
process.on('uncaughtException', (err) => { process.on('uncaughtException', (err) => {
this.logErrorWithOriginalStack(err, 'uncaughtException') this.logErrorWithOriginalStack(err, 'uncaughtException')
}) })
......
...@@ -14,6 +14,10 @@ import { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler' ...@@ -14,6 +14,10 @@ import { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'
import { serveStatic } from '../serve-static' import { serveStatic } from '../serve-static'
import setupDebug from 'next/dist/compiled/debug' import setupDebug from 'next/dist/compiled/debug'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import {
isUnhandledRejectionListenerRegistered,
registerUnhandledRejectionListener,
} from '../node-environment-extensions/process-error-handlers'
import { DecodeError } from '../../shared/lib/utils' import { DecodeError } from '../../shared/lib/utils'
import { findPagesDir } from '../../lib/find-pages-dir' import { findPagesDir } from '../../lib/find-pages-dir'
import { setupFsCheck } from './router-utils/filesystem' import { setupFsCheck } from './router-utils/filesystem'
...@@ -874,24 +878,23 @@ export async function initialize(opts: { ...@@ -874,24 +878,23 @@ export async function initialize(opts: {
), ),
} }
const logError = async ( const logError = async (err: Error | undefined) => {
type: 'uncaughtException' | 'unhandledRejection',
err: Error | undefined
) => {
if (isPostpone(err)) { if (isPostpone(err)) {
// React postpones that are unhandled might end up logged here but they're // React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering. // not really errors. They're just part of rendering.
return return
} }
if (type === 'unhandledRejection') { Log.error('uncaughtException: ', err)
Log.error('unhandledRejection: ', err)
} else if (type === 'uncaughtException') {
Log.error('uncaughtException: ', err)
}
} }
process.on('uncaughtException', logError.bind(null, 'uncaughtException')) process.on('uncaughtException', logError)
process.on('unhandledRejection', logError.bind(null, 'unhandledRejection'))
// The render server may run in the same process and have already registered
// the unhandled rejection listener, in which case we must not register
// another one, to avoid logging unhandled rejections multiple times.
if (!isUnhandledRejectionListenerRegistered()) {
registerUnhandledRejectionListener()
}
const resolveRoutes = getResolveRoutes( const resolveRoutes = getResolveRoutes(
fsChecker, fsChecker,
......
import { isPostpone } from '../lib/router-utils/is-postpone' import { isPostpone } from '../lib/router-utils/is-postpone'
import * as Log from '../../build/output/log'
let _global = globalThis as typeof globalThis & { let _global = globalThis as typeof globalThis & {
nextInitializedProcessErrorHandlers?: boolean nextInitializedProcessErrorHandlers?: boolean
[UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener
}
// The listener function is shared via globalThis so that multiple copies of
// this module (e.g. in the pre-compiled server bundle and in a route module
// bundle) still register and detect a single listener instance.
const UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(
'next.unhandledRejectionListener'
)
function unhandledRejectionListener(reason: unknown) {
if (isPostpone(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
// Immediately log the error.
// TODO: Ideally, if we knew that this error was triggered by application
// code, we would suppress it entirely without logging. We can't reliably
// detect all of these, but when cacheComponents is enabled, we could suppress
// at least some of them by waiting to log the error until after all in-
// progress renders have completed. Then, only log errors for which there
// was not a corresponding "rejectionHandled" event.
Log.error('unhandledRejection:', reason)
}
/**
* Checks if the Next.js unhandled rejection listener is currently attached.
* This queries the actual process listeners instead of relying on a module
* global, so it stays accurate even if the listener was removed externally,
* e.g. via `process.removeAllListeners('unhandledRejection')`.
*/
export function isUnhandledRejectionListenerRegistered(): boolean {
const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]
return (
listener !== undefined &&
process.listeners('unhandledRejection').includes(listener)
)
}
/**
* Registers the Next.js unhandled rejection listener, which logs unhandled
* rejections (except React postpones) and prevents them from crashing the
* process. Safe to call unconditionally: if the listener is already attached,
* this is a no-op, so it never registers a duplicate.
*/
export function registerUnhandledRejectionListener(): void {
if (isUnhandledRejectionListenerRegistered()) {
return
}
const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=
unhandledRejectionListener)
process.on('unhandledRejection', listener)
} }
export function installProcessErrorHandlers( export function installProcessErrorHandlers(
shouldRemoveUncaughtErrorAndRejectionListeners: boolean shouldRemoveUncaughtErrorAndRejectionListeners: boolean
) { ) {
if (_global.nextInitializedProcessErrorHandlers) return if (!_global.nextInitializedProcessErrorHandlers) {
_global.nextInitializedProcessErrorHandlers = true _global.nextInitializedProcessErrorHandlers = true
// The conventional wisdom of Node.js and other runtimes is to treat // The conventional wisdom of Node.js and other runtimes is to treat
// unhandled errors as fatal and exit the process. // unhandled errors as fatal and exit the process.
// //
// But Next.js is not a generic JS runtime — it's a specialized runtime for // But Next.js is not a generic JS runtime — it's a specialized runtime for
// React Server Components. // React Server Components.
// //
// Many unhandled rejections are due to the late-awaiting pattern for // Many unhandled rejections are due to the late-awaiting pattern for
// prefetching data. In Next.js it's OK to call an async function without // prefetching data. In Next.js it's OK to call an async function without
// immediately awaiting it, to start the request as soon as possible // immediately awaiting it, to start the request as soon as possible
// without blocking unncessarily on the result. These can end up // without blocking unncessarily on the result. These can end up
// triggering an "unhandledRejection" if it later turns out that the // triggering an "unhandledRejection" if it later turns out that the
// data is not needed to render the page. Example: // data is not needed to render the page. Example:
// //
// const promise = fetchData() // const promise = fetchData()
// const shouldShow = await checkCondition() // const shouldShow = await checkCondition()
// if (shouldShow) { // if (shouldShow) {
// return <Component promise={promise} /> // return <Component promise={promise} />
// } // }
// //
// In this example, `fetchData` is called immediately to start the request // In this example, `fetchData` is called immediately to start the request
// as soon as possible, but if `shouldShow` is false, then it will be // as soon as possible, but if `shouldShow` is false, then it will be
// discarded without unwrapping its result. If it errors, it will trigger // discarded without unwrapping its result. If it errors, it will trigger
// an "unhandledRejection" event. // an "unhandledRejection" event.
// //
// Ideally, we would suppress these rejections completely without warning, // Ideally, we would suppress these rejections completely without warning,
// because we don't consider them real errors. (TODO: Currently we do warn.) // because we don't consider them real errors. (TODO: Currently we do warn.)
// //
// But regardless of whether we do or don't warn, we definitely shouldn't // But regardless of whether we do or don't warn, we definitely shouldn't
// crash the entire process. // crash the entire process.
// //
// Even a "legit" unhandled error unrelated to prefetching shouldn't // Even a "legit" unhandled error unrelated to prefetching shouldn't
// prevent the rest of the page from rendering. // prevent the rest of the page from rendering.
// //
// So, we're going to intentionally override the default error handling // So, we're going to intentionally override the default error handling
// behavior of the outer JS runtime to be more forgiving // behavior of the outer JS runtime to be more forgiving
// Remove any existing "unhandledRejection" and "uncaughtException" handlers.
// This is gated behind an experimental flag until we've considered the impact
// in various deployment environments. It's possible this may always need to
// be configurable.
if (shouldRemoveUncaughtErrorAndRejectionListeners) {
process.removeAllListeners('uncaughtException')
process.removeAllListeners('unhandledRejection')
}
// Install a new handler to prevent the process from crashing. // Remove any existing "unhandledRejection" and "uncaughtException" handlers.
process.on('unhandledRejection', (reason: unknown) => { // This is gated behind an experimental flag until we've considered the impact
if (isPostpone(reason)) { // in various deployment environments. It's possible this may always need to
// React postpones that are unhandled might end up logged here but they're // be configurable.
// not really errors. They're just part of rendering. if (shouldRemoveUncaughtErrorAndRejectionListeners) {
return process.removeAllListeners('uncaughtException')
process.removeAllListeners('unhandledRejection')
} }
// Immediately log the error.
// TODO: Ideally, if we knew that this error was triggered by application
// code, we would suppress it entirely without logging. We can't reliably
// detect all of these, but when cacheComponents is enabled, we could suppress
// at least some of them by waiting to log the error until after all in-
// progress renders have completed. Then, only log errors for which there
// was not a corresponding "rejectionHandled" event.
console.error(reason)
})
process.on('rejectionHandled', () => { process.on('rejectionHandled', () => {
// TODO: See note in the unhandledRejection handler above. In the future, // TODO: See note in the unhandledRejection listener above. In the
// we may use the "rejectionHandled" event to de-queue an error from // future, we may use the "rejectionHandled" event to de-queue an error
// being logged. // from being logged.
}) })
// Unhandled exceptions are errors triggered by non-async functions, so this // Unhandled exceptions are errors triggered by non-async functions, so this
// is unrelated to the late-awaiting pattern. However, for similar reasons, // is unrelated to the late-awaiting pattern. However, for similar reasons,
// we still shouldn't crash the process. Just log it. // we still shouldn't crash the process. Just log it.
process.on('uncaughtException', (reason: unknown) => { process.on('uncaughtException', (reason: unknown) => {
if (isPostpone(reason)) { if (isPostpone(reason)) {
return return
} }
console.error(reason) console.error(reason)
}) })
}
// Register the listener unconditionally, and not only during the guarded
// initialization above: a previous registration may have been undone by the
// `removeAllListeners` call of a later `installProcessErrorHandlers` call
// (or by external code), and registering is a no-op if the listener is
// still attached.
registerUnhandledRejectionListener()
} }
...@@ -136,17 +136,17 @@ describe('middleware - development errors', () => { ...@@ -136,17 +136,17 @@ describe('middleware - development errors', () => {
}) })
expect(stripAnsi(next.cliOutput)).toContain( expect(stripAnsi(next.cliOutput)).toContain(
isTurbopack isTurbopack
? '⨯ unhandledRejection: Error: async boom!' + ? '⨯ unhandledRejection: Error: async boom!' +
'\n at throwError (middleware.js:4:15)' + '\n at throwError (middleware.js:4:15)' +
// TODO(veil): Sourcemap to original name i.e. "default" // TODO(veil): Sourcemap to original name i.e. "default"
'\n at __TURBOPACK__default__export__ (middleware.js:7:9)' + '\n at __TURBOPACK__default__export__ (middleware.js:7:9)' +
"\n 2 | import { NextResponse } from 'next/server'" "\n 2 | import { NextResponse } from 'next/server'"
: isRspack : isRspack
? '\n⨯ unhandledRejection: Error: async boom!' + ? '\n⨯ unhandledRejection: Error: async boom!' +
'\n at throwError (middleware.js:4:15)' + '\n at throwError (middleware.js:4:15)' +
'\n at __rspack_default_export (middleware.js:7:9)' + '\n at __rspack_default_export (middleware.js:7:9)' +
"\n 2 | import { NextResponse } from 'next/server'" "\n 2 | import { NextResponse } from 'next/server'"
: '\n⨯ unhandledRejection: Error: async boom!' + : '\n⨯ unhandledRejection: Error: async boom!' +
'\n at throwError (middleware.js:4:15)' + '\n at throwError (middleware.js:4:15)' +
'\n at default (middleware.js:7:9)' + '\n at default (middleware.js:7:9)' +
"\n 2 | import { NextResponse } from 'next/server'" "\n 2 | import { NextResponse } from 'next/server'"
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
async function throwError() {
throw new Error('test unhandled rejection')
}
async function UnhandledRejectionLogging() {
await connection()
void throwError()
await Promise.resolve() // Ensure the error is thrown asynchronously
return <div>Unhandled Rejection Logging</div>
}
export default function Page() {
return (
<Suspense>
<UnhandledRejectionLogging />
</Suspense>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
describe('unhandled-rejection-logging', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('logs an unhandled rejection', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/')
await retry(async () => {
expect(next.cliOutput.slice(outputIndex)).toContain('unhandledRejection')
})
// Give the remaining listeners a chance to log before asserting.
await waitFor(1000)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
// The rejection must be logged exactly once, by the single registered
// listener, and not additionally by other process listeners.
expect(cliOutput).toContain(
'⨯ unhandledRejection: Error: test unhandled rejection'
)
expect(cliOutput.split('Error: test unhandled rejection').length - 1).toBe(
1
)
})
})
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