Unverified Commit 3cce038a authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Reduce console error patching (#67433)

### What

Remove few places of patching `console.error`.
- We were using `patchConsole` to only access the error state for hydration errors, they can actually be merged into other console.error override.
- We override `console.error` twice in both client entry of app router and the hydration error handler. Merge the later one into former one.
parent 1c10e1b2
......@@ -9,33 +9,33 @@ import { createFromReadableStream } from 'react-server-dom-webpack/client'
import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime'
import { onRecoverableError } from './on-recoverable-error'
import { callServer } from './app-call-server'
import { isNextRouterError } from './components/is-next-router-error'
import {
ActionQueueContext,
createMutableActionQueue,
} from '../shared/lib/router/action-queue'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types'
import { isNextRouterError } from './components/is-next-router-error'
import { handleClientError } from './components/react-dev-overlay/internal/helpers/use-error-handler'
// Since React doesn't call onerror for errors caught in error boundaries.
// Patch console.error to collect information about hydration errors
const origConsoleError = window.console.error
window.console.error = (...args) => {
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
if (
process.env.NODE_ENV !== 'production'
? isNextRouterError(args[1])
: isNextRouterError(args[0])
) {
return
}
origConsoleError.apply(window.console, args)
}
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0]
if (!isNextRouterError(error)) {
if (process.env.NODE_ENV !== 'production') {
const storeHydrationErrorStateFromConsoleArgs =
require('./components/react-dev-overlay/internal/helpers/hydration-error-info')
.storeHydrationErrorStateFromConsoleArgs as typeof import('./components/react-dev-overlay/internal/helpers/hydration-error-info').storeHydrationErrorStateFromConsoleArgs
storeHydrationErrorStateFromConsoleArgs()
storeHydrationErrorStateFromConsoleArgs(...args)
handleClientError(error)
}
window.addEventListener('error', (ev: WindowEventMap['error']): void => {
if (isNextRouterError(ev.error)) {
ev.preventDefault()
return
origConsoleError.apply(window.console, args)
}
})
}
/// <reference types="react-dom/experimental" />
......@@ -203,16 +203,6 @@ export function hydrate() {
const isError =
document.documentElement.id === '__next_error__' || hasMissingTags
if (process.env.NODE_ENV !== 'production') {
// Patch console.error to collect information about hydration errors
const patchConsoleError =
require('./components/react-dev-overlay/internal/helpers/hydration-error-info')
.patchConsoleError as typeof import('./components/react-dev-overlay/internal/helpers/hydration-error-info').patchConsoleError
if (!isError) {
patchConsoleError()
}
}
if (isError) {
if (process.env.NODE_ENV !== 'production') {
// if an error is thrown while rendering an RSC stream, this will catch it in dev
......
......@@ -65,22 +65,18 @@ export const getReactHydrationDiffSegments = (msg: NullableText) => {
* When the hydration runtime error is thrown, the message and component stack are added to the error.
* This results in a more helpful error message in the error overlay.
*/
export function patchConsoleError() {
const prev = console.error
console.error = function (msg, serverContent, clientContent, componentStack) {
if (isKnownHydrationWarning(msg)) {
hydrationErrorState.warning = [
// remove the last %s from the message
msg,
serverContent,
clientContent,
]
hydrationErrorState.componentStack = componentStack
hydrationErrorState.serverContent = serverContent
hydrationErrorState.clientContent = clientContent
}
// @ts-expect-error argument is defined
prev.apply(console, arguments)
export function storeHydrationErrorStateFromConsoleArgs(...args: any[]) {
const [msg, serverContent, clientContent, componentStack] = args
if (isKnownHydrationWarning(msg)) {
hydrationErrorState.warning = [
// remove the last %s from the message
msg,
serverContent,
clientContent,
]
hydrationErrorState.componentStack = componentStack
hydrationErrorState.serverContent = serverContent
hydrationErrorState.clientContent = clientContent
}
}
......@@ -24,71 +24,63 @@ const rejectionQueue: Array<Error> = []
const errorHandlers: Array<ErrorHandler> = []
const rejectionHandlers: Array<ErrorHandler> = []
if (typeof window !== 'undefined') {
function handleError(error: unknown) {
if (isNextRouterError(error)) {
return false
}
if (
!error ||
!(error instanceof Error) ||
typeof error.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}
export function handleClientError(error: unknown) {
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
}
const isCausedByHydrationFailure = isHydrationError(error)
if (
isHydrationError(error) &&
!error.message.includes(
'https://nextjs.org/docs/messages/react-hydration-error'
)
) {
const reactHydrationDiffSegments = getReactHydrationDiffSegments(
error.message
)
let parsedHydrationErrorState: typeof hydrationErrorState = {}
if (reactHydrationDiffSegments) {
const isCausedByHydrationFailure = isHydrationError(error)
if (
isHydrationError(error) &&
!error.message.includes(
'https://nextjs.org/docs/messages/react-hydration-error'
)
) {
const reactHydrationDiffSegments = getReactHydrationDiffSegments(
error.message
)
let parsedHydrationErrorState: typeof hydrationErrorState = {}
if (reactHydrationDiffSegments) {
parsedHydrationErrorState = {
...(error as any).details,
...hydrationErrorState,
warning: hydrationErrorState.warning || [
getDefaultHydrationErrorMessage(),
],
notes: reactHydrationDiffSegments[0],
reactOutputComponentDiff: reactHydrationDiffSegments[1],
}
} else {
// If there's any extra information in the error message to display,
// append it to the error message details property
if (hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
parsedHydrationErrorState = {
...(error as any).details,
// It contains the warning, component stack, server and client tag names
...hydrationErrorState,
warning: hydrationErrorState.warning || [
getDefaultHydrationErrorMessage(),
],
notes: reactHydrationDiffSegments[0],
reactOutputComponentDiff: reactHydrationDiffSegments[1],
}
} else {
// If there's any extra information in the error message to display,
// append it to the error message details property
if (hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
parsedHydrationErrorState = {
...(error as any).details,
// It contains the warning, component stack, server and client tag names
...hydrationErrorState,
}
}
error.message +=
'\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error'
}
;(error as any).details = parsedHydrationErrorState
error.message +=
'\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error'
}
;(error as any).details = parsedHydrationErrorState
}
// Only queue one hydration every time
if (isCausedByHydrationFailure) {
if (!hasHydrationError) {
errorQueue.push(error)
}
hasHydrationError = true
}
for (const handler of errorHandlers) {
handler(error)
// Only queue one hydration every time
if (isCausedByHydrationFailure) {
if (!hasHydrationError) {
errorQueue.push(error)
}
hasHydrationError = true
}
for (const handler of errorHandlers) {
handler(error)
}
}
if (typeof window !== 'undefined') {
// These event handlers must be added outside of the hook because there is no
// guarantee that the hook will be alive in a mounted component in time to
// when the errors occur.
......@@ -96,21 +88,14 @@ if (typeof window !== 'undefined') {
window.addEventListener(
'error',
(event: WindowEventMap['error']): void | boolean => {
if (handleError(event.error) === false) {
if (isNextRouterError(event.error)) {
event.preventDefault()
return false
}
handleClientError(event.error)
}
)
// caught errors go through console.error
const origConsoleError = window.console.error
window.console.error = (...args) => {
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0]
if (handleError(error) !== false) {
origConsoleError.apply(window.console, args)
}
}
window.addEventListener(
'unhandledrejection',
(ev: WindowEventMap['unhandledrejection']): void => {
......
......@@ -4,7 +4,7 @@ import { parseComponentStack } from '../internal/helpers/parse-component-stack'
import {
getReactHydrationDiffSegments,
hydrationErrorState,
patchConsoleError,
storeHydrationErrorStateFromConsoleArgs,
} from '../internal/helpers/hydration-error-info'
import {
ACTION_BEFORE_REFRESH,
......@@ -21,9 +21,6 @@ import {
isHydrationError,
} from '../../is-hydration-error'
// Patch console.error to collect information about hydration errors
patchConsoleError()
let isRegistered = false
let stackTraceLimit: number | undefined = undefined
......@@ -93,6 +90,7 @@ let origConsoleError = console.error
function nextJsHandleConsoleError(...args: any[]) {
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0]
storeHydrationErrorStateFromConsoleArgs(...args)
handleError(error)
origConsoleError.apply(window.console, args)
}
......
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