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
import { LRUCache } from '../lib/lru-cache'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
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 { buildCustomRoute } from '../../lib/build-custom-route'
import { decorateServerError } from '../../shared/lib/error-source'
......@@ -378,14 +381,14 @@ export default class DevServer extends Server {
setGlobal('telemetry', telemetry)
}
process.on('unhandledRejection', (reason) => {
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
// The router server or 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()
}
this.logErrorWithOriginalStack(reason, 'unhandledRejection')
})
process.on('uncaughtException', (err) => {
this.logErrorWithOriginalStack(err, 'uncaughtException')
})
......
......@@ -14,6 +14,10 @@ import { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'
import { serveStatic } from '../serve-static'
import setupDebug from 'next/dist/compiled/debug'
import * as Log from '../../build/output/log'
import {
isUnhandledRejectionListenerRegistered,
registerUnhandledRejectionListener,
} from '../node-environment-extensions/process-error-handlers'
import { DecodeError } from '../../shared/lib/utils'
import { findPagesDir } from '../../lib/find-pages-dir'
import { setupFsCheck } from './router-utils/filesystem'
......@@ -874,24 +878,23 @@ export async function initialize(opts: {
),
}
const logError = async (
type: 'uncaughtException' | 'unhandledRejection',
err: Error | undefined
) => {
const logError = async (err: Error | undefined) => {
if (isPostpone(err)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
if (type === 'unhandledRejection') {
Log.error('unhandledRejection: ', err)
} else if (type === 'uncaughtException') {
Log.error('uncaughtException: ', err)
}
}
process.on('uncaughtException', logError.bind(null, 'uncaughtException'))
process.on('unhandledRejection', logError.bind(null, 'unhandledRejection'))
process.on('uncaughtException', logError)
// 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(
fsChecker,
......
import { isPostpone } from '../lib/router-utils/is-postpone'
import * as Log from '../../build/output/log'
let _global = globalThis as typeof globalThis & {
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(
shouldRemoveUncaughtErrorAndRejectionListeners: boolean
) {
if (_global.nextInitializedProcessErrorHandlers) return
if (!_global.nextInitializedProcessErrorHandlers) {
_global.nextInitializedProcessErrorHandlers = true
// The conventional wisdom of Node.js and other runtimes is to treat
// unhandled errors as fatal and exit the process.
......@@ -54,27 +111,10 @@ export function installProcessErrorHandlers(
process.removeAllListeners('unhandledRejection')
}
// Install a new handler to prevent the process from crashing.
process.on('unhandledRejection', (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.
console.error(reason)
})
process.on('rejectionHandled', () => {
// TODO: See note in the unhandledRejection handler above. In the future,
// we may use the "rejectionHandled" event to de-queue an error from
// being logged.
// TODO: See note in the unhandledRejection listener above. In the
// future, we may use the "rejectionHandled" event to de-queue an error
// from being logged.
})
// Unhandled exceptions are errors triggered by non-async functions, so this
......@@ -86,4 +126,12 @@ export function installProcessErrorHandlers(
}
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()
}
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