Unverified Commit 8c1e3d94 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

refactor: move the global client error code (#74699)

### What

Refactor the code that responsible for global client error handling,
since they could touch shared state so they shouldn't be forked in new
error overlay as hooks or utils. Hence I deleted the forked ones, and
move the existing used ones to the `/errors/` to avoid getting
duplicated.
parent 0d81c3c6
import { import {
isHydrationError, isHydrationError,
getDefaultHydrationErrorMessage, getDefaultHydrationErrorMessage,
} from '../../../is-hydration-error' } from '../is-hydration-error'
import { import {
hydrationErrorState, hydrationErrorState,
getReactHydrationDiffSegments, getReactHydrationDiffSegments,
......
import { isHydrationError } from '../../../is-hydration-error' import { isHydrationError } from '../is-hydration-error'
// Dedupe the two consecutive errors: If the previous one is same as current one, ignore the current one. // Dedupe the two consecutive errors: If the previous one is same as current one, ignore the current one.
export function enqueueConsecutiveDedupedError( export function enqueueConsecutiveDedupedError(
......
import { getHydrationErrorStackInfo } from '../../../is-hydration-error' import { getHydrationErrorStackInfo } from '../is-hydration-error'
export type HydrationErrorState = { export type HydrationErrorState = {
// Hydration warning template format: <message> <serverContent> <clientContent> // Hydration warning template format: <message> <serverContent> <clientContent>
......
import React from 'react' import React from 'react'
import isError from '../../../../../lib/is-error' import isError from '../../../lib/is-error'
const REACT_ERROR_STACK_BOTTOM_FRAME = 'react-stack-bottom-frame' const REACT_ERROR_STACK_BOTTOM_FRAME = 'react-stack-bottom-frame'
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = new RegExp( const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = new RegExp(
......
import { useEffect } from 'react' import { useEffect } from 'react'
import { attachHydrationErrorState } from './attach-hydration-error-state' import { attachHydrationErrorState } from './attach-hydration-error-state'
import { isNextRouterError } from '../../../is-next-router-error' import { isNextRouterError } from '../is-next-router-error'
import { storeHydrationErrorStateFromConsoleArgs } from './hydration-error-info' import { storeHydrationErrorStateFromConsoleArgs } from './hydration-error-info'
import { formatConsoleArgs } from '../../../../lib/console' import { formatConsoleArgs } from '../../lib/console'
import isError from '../../../../../lib/is-error' import isError from '../../../lib/is-error'
import { createUnhandledError } from './console-error' import { createUnhandledError } from './console-error'
import { enqueueConsecutiveDedupedError } from './enqueue-client-error' import { enqueueConsecutiveDedupedError } from './enqueue-client-error'
import { getReactStitchedError } from './stitched-error' import { getReactStitchedError } from '../errors/stitched-error'
const queueMicroTask = const queueMicroTask =
globalThis.queueMicrotask || ((cb: () => void) => Promise.resolve().then(cb)) globalThis.queueMicrotask || ((cb: () => void) => Promise.resolve().then(cb))
......
import { handleGlobalErrors } from '../react-dev-overlay/internal/helpers/use-error-handler' import { handleGlobalErrors } from '../errors/use-error-handler'
handleGlobalErrors() handleGlobalErrors()
import isError from '../../../lib/is-error' import isError from '../../../lib/is-error'
import { isNextRouterError } from '../is-next-router-error' import { isNextRouterError } from '../is-next-router-error'
import { handleClientError } from '../react-dev-overlay/internal/helpers/use-error-handler' import { handleClientError } from '../errors/use-error-handler'
export const originConsoleError = window.console.error export const originConsoleError = window.console.error
......
...@@ -18,11 +18,11 @@ import { PseudoHtmlDiff } from './RuntimeError/component-stack-pseudo-html' ...@@ -18,11 +18,11 @@ import { PseudoHtmlDiff } from './RuntimeError/component-stack-pseudo-html'
import { import {
type HydrationErrorState, type HydrationErrorState,
getHydrationWarningType, getHydrationWarningType,
} from '../helpers/hydration-error-info' } from '../../../../errors/hydration-error-info'
import { import {
getUnhandledErrorType, getUnhandledErrorType,
isUnhandledConsoleOrRejection, isUnhandledConsoleOrRejection,
} from '../helpers/console-error' } from '../../../../errors/console-error'
import { extractNextErrorCode } from '../../../../../../lib/error-telemetry-utils' import { extractNextErrorCode } from '../../../../../../lib/error-telemetry-utils'
import { DevToolsIndicator } from '../components/Errors/dev-tools-indicator/dev-tools-indicator' import { DevToolsIndicator } from '../components/Errors/dev-tools-indicator/dev-tools-indicator'
import { ErrorOverlayLayout } from '../components/Errors/error-overlay-layout/error-overlay-layout' import { ErrorOverlayLayout } from '../components/Errors/error-overlay-layout/error-overlay-layout'
......
import {
isHydrationError,
getDefaultHydrationErrorMessage,
} from '../../../../is-hydration-error'
import {
hydrationErrorState,
getReactHydrationDiffSegments,
} from './hydration-error-info'
export function attachHydrationErrorState(error: 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,
}
}
}
;(error as any).details = parsedHydrationErrorState
}
}
import { isHydrationError } from '../../../../is-hydration-error'
// Dedupe the two consecutive errors: If the previous one is same as current one, ignore the current one.
export function enqueueConsecutiveDedupedError(
queue: Array<Error>,
error: Error
) {
const isFront = isHydrationError(error)
const previousError = isFront ? queue[0] : queue[queue.length - 1]
// Compare the error stack to dedupe the consecutive errors
if (previousError && previousError.stack === error.stack) {
return
}
// TODO: change all to push error into errorQueue,
// currently there's a async api error is always erroring while hydration error showing up.
// Move hydration error to the front of the queue to unblock.
if (isFront) {
queue.unshift(error)
} else {
queue.push(error)
}
}
import { getHydrationErrorStackInfo } from '../../../../is-hydration-error'
export type HydrationErrorState = {
// Hydration warning template format: <message> <serverContent> <clientContent>
warning?: [string, string, string]
componentStack?: string
serverContent?: string
clientContent?: string
// React 19 hydration diff format: <notes> <link> <component diff?>
notes?: string
reactOutputComponentDiff?: string
}
type NullableText = string | null | undefined
export const hydrationErrorState: HydrationErrorState = {}
// https://github.com/facebook/react/blob/main/packages/react-dom/src/__tests__/ReactDOMHydrationDiff-test.js used as a reference
const htmlTagsWarnings = new Set([
'Warning: In HTML, %s cannot be a child of <%s>.%s\nThis will cause a hydration error.%s',
'Warning: In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s',
'Warning: In HTML, text nodes cannot be a child of <%s>.\nThis will cause a hydration error.',
"Warning: In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.",
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s',
])
const textAndTagsMismatchWarnings = new Set([
'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s',
'Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s',
])
const textMismatchWarning =
'Warning: Text content did not match. Server: "%s" Client: "%s"%s'
export const getHydrationWarningType = (
message: NullableText
): 'tag' | 'text' | 'text-in-tag' => {
if (typeof message !== 'string') {
// TODO: Doesn't make sense to treat no message as a hydration error message.
// We should bail out somewhere earlier.
return 'text'
}
const normalizedMessage = message.startsWith('Warning: ')
? message
: `Warning: ${message}`
if (isHtmlTagsWarning(normalizedMessage)) return 'tag'
if (isTextInTagsMismatchWarning(normalizedMessage)) return 'text-in-tag'
return 'text'
}
const isHtmlTagsWarning = (message: string) => htmlTagsWarnings.has(message)
const isTextMismatchWarning = (message: string) =>
textMismatchWarning === message
const isTextInTagsMismatchWarning = (msg: string) =>
textAndTagsMismatchWarnings.has(msg)
const isKnownHydrationWarning = (message: NullableText) => {
if (typeof message !== 'string') {
return false
}
// React 18 has the `Warning: ` prefix.
// React 19 does not.
const normalizedMessage = message.startsWith('Warning: ')
? message
: `Warning: ${message}`
return (
isHtmlTagsWarning(normalizedMessage) ||
isTextInTagsMismatchWarning(normalizedMessage) ||
isTextMismatchWarning(normalizedMessage)
)
}
export const getReactHydrationDiffSegments = (msg: NullableText) => {
if (msg) {
const { message, diff } = getHydrationErrorStackInfo(msg)
if (message) return [message, diff]
}
return undefined
}
/**
* Patch console.error to capture hydration errors.
* If any of the knownHydrationWarnings are logged, store the message and component stack.
* 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 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
}
}
import React from 'react'
import isError from '../../../../../../lib/is-error'
const REACT_ERROR_STACK_BOTTOM_FRAME = 'react-stack-bottom-frame'
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = new RegExp(
`(at ${REACT_ERROR_STACK_BOTTOM_FRAME} )|(${REACT_ERROR_STACK_BOTTOM_FRAME}\\@)`
)
const captureOwnerStack = (React as any).captureOwnerStack
? (React as any).captureOwnerStack
: () => ''
export function getReactStitchedError<T = unknown>(err: T): Error | T {
if (typeof (React as any).captureOwnerStack !== 'function') {
return err
}
const isErrorInstance = isError(err)
const originStack = isErrorInstance ? err.stack || '' : ''
const originMessage = isErrorInstance ? err.message : ''
const stackLines = originStack.split('\n')
const indexOfSplit = stackLines.findIndex((line) =>
REACT_ERROR_STACK_BOTTOM_FRAME_REGEX.test(line)
)
const isOriginalReactError = indexOfSplit >= 0 // has the react-stack-bottom-frame
let newStack = isOriginalReactError
? stackLines.slice(0, indexOfSplit).join('\n')
: originStack
const newError = new Error(originMessage)
// Copy all enumerable properties, e.g. digest
Object.assign(newError, err)
newError.stack = newStack
// Avoid duplicate overriding stack frames
appendOwnerStack(newError)
return newError
}
function appendOwnerStack(error: Error) {
let stack = error.stack || ''
// Avoid duplicate overriding stack frames
const ownerStack = captureOwnerStack()
if (ownerStack && stack.endsWith(ownerStack) === false) {
stack += ownerStack
// Override stack
error.stack = stack
}
}
...@@ -9,7 +9,7 @@ import { ComponentStyles } from '../internal/styles/ComponentStyles' ...@@ -9,7 +9,7 @@ import { ComponentStyles } from '../internal/styles/ComponentStyles'
import { CssReset } from '../internal/styles/CssReset' import { CssReset } from '../internal/styles/CssReset'
import { RootLayoutMissingTagsError } from '../internal/container/RootLayoutMissingTagsError' import { RootLayoutMissingTagsError } from '../internal/container/RootLayoutMissingTagsError'
import type { Dispatcher } from './hot-reloader-client' import type { Dispatcher } from './hot-reloader-client'
import { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
interface ReactDevOverlayState { interface ReactDevOverlayState {
isReactError: boolean isReactError: boolean
......
...@@ -24,8 +24,8 @@ import { ...@@ -24,8 +24,8 @@ import {
} from '../shared' } from '../shared'
import { parseStack } from '../internal/helpers/parse-stack' import { parseStack } from '../internal/helpers/parse-stack'
import ReactDevOverlay from './ReactDevOverlay' import ReactDevOverlay from './ReactDevOverlay'
import { useErrorHandler } from '../internal/helpers/use-error-handler' import { useErrorHandler } from '../../errors/use-error-handler'
import { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import { import {
useSendMessage, useSendMessage,
useTurbopack, useTurbopack,
...@@ -41,10 +41,10 @@ import type { ...@@ -41,10 +41,10 @@ import type {
} from '../../../../server/dev/hot-reloader-types' } from '../../../../server/dev/hot-reloader-types'
import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message' import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared' import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import type { HydrationErrorState } from '../internal/helpers/hydration-error-info' import type { HydrationErrorState } from '../../errors/hydration-error-info'
import type { DebugInfo } from '../types' import type { DebugInfo } from '../types'
import { useUntrackedPathname } from '../../navigation-untracked' import { useUntrackedPathname } from '../../navigation-untracked'
import { getReactStitchedError } from '../internal/helpers/stitched-error' import { getReactStitchedError } from '../../errors/stitched-error'
import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-while-rendering-rsc' import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-while-rendering-rsc'
import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events' import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events'
......
...@@ -28,13 +28,13 @@ import { PseudoHtmlDiff } from './RuntimeError/component-stack-pseudo-html' ...@@ -28,13 +28,13 @@ import { PseudoHtmlDiff } from './RuntimeError/component-stack-pseudo-html'
import { import {
type HydrationErrorState, type HydrationErrorState,
getHydrationWarningType, getHydrationWarningType,
} from '../helpers/hydration-error-info' } from '../../../errors/hydration-error-info'
import { NodejsInspectorCopyButton } from '../components/nodejs-inspector' import { NodejsInspectorCopyButton } from '../components/nodejs-inspector'
import { CopyButton } from '../components/copy-button' import { CopyButton } from '../components/copy-button'
import { import {
getUnhandledErrorType, getUnhandledErrorType,
isUnhandledConsoleOrRejection, isUnhandledConsoleOrRejection,
} from '../helpers/console-error' } from '../../../errors/console-error'
import { extractNextErrorCode } from '../../../../../lib/error-telemetry-utils' import { extractNextErrorCode } from '../../../../../lib/error-telemetry-utils'
export type SupportedErrorEvent = { export type SupportedErrorEvent = {
......
// To distinguish from React error.digest, we use a different symbol here to determine if the error is from console.error or unhandled promise rejection.
const digestSym = Symbol.for('next.console.error.digest')
const consoleTypeSym = Symbol.for('next.console.error.type')
// Represent non Error shape unhandled promise rejections or console.error errors.
// Those errors will be captured and displayed in Error Overlay.
type UnhandledError = Error & {
[digestSym]: 'NEXT_UNHANDLED_ERROR'
[consoleTypeSym]: 'string' | 'error'
}
export function createUnhandledError(message: string | Error): UnhandledError {
const error = (
typeof message === 'string' ? new Error(message) : message
) as UnhandledError
error[digestSym] = 'NEXT_UNHANDLED_ERROR'
error[consoleTypeSym] = typeof message === 'string' ? 'string' : 'error'
return error
}
export const isUnhandledConsoleOrRejection = (
error: any
): error is UnhandledError => {
return error && error[digestSym] === 'NEXT_UNHANDLED_ERROR'
}
export const getUnhandledErrorType = (error: UnhandledError) => {
return error[consoleTypeSym]
}
...@@ -4,7 +4,7 @@ import { parseComponentStack } from '../internal/helpers/parse-component-stack' ...@@ -4,7 +4,7 @@ import { parseComponentStack } from '../internal/helpers/parse-component-stack'
import { import {
hydrationErrorState, hydrationErrorState,
storeHydrationErrorStateFromConsoleArgs, storeHydrationErrorStateFromConsoleArgs,
} from '../internal/helpers/hydration-error-info' } from '../../errors/hydration-error-info'
import { import {
ACTION_BEFORE_REFRESH, ACTION_BEFORE_REFRESH,
ACTION_BUILD_ERROR, ACTION_BUILD_ERROR,
...@@ -15,7 +15,7 @@ import { ...@@ -15,7 +15,7 @@ import {
ACTION_VERSION_INFO, ACTION_VERSION_INFO,
} from '../shared' } from '../shared'
import type { VersionInfo } from '../../../../server/dev/parse-version-info' import type { VersionInfo } from '../../../../server/dev/parse-version-info'
import { attachHydrationErrorState } from '../internal/helpers/attach-hydration-error-state' import { attachHydrationErrorState } from '../../errors/attach-hydration-error-state'
let isRegistered = false let isRegistered = false
let stackTraceLimit: number | undefined = undefined let stackTraceLimit: number | undefined = undefined
......
...@@ -46,7 +46,7 @@ import type { ...@@ -46,7 +46,7 @@ import type {
} from '../../../../server/dev/hot-reloader-types' } from '../../../../server/dev/hot-reloader-types'
import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message' import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared' import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
// This alternative WebpackDevServer combines the functionality of: // This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
......
...@@ -11,7 +11,7 @@ import { ...@@ -11,7 +11,7 @@ import {
urlQueryToSearchParams, urlQueryToSearchParams,
} from '../shared/lib/router/utils/querystring' } from '../shared/lib/router/utils/querystring'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types' import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types'
import { RuntimeErrorHandler } from './components/react-dev-overlay/internal/helpers/runtime-error-handler' import { RuntimeErrorHandler } from './components/errors/runtime-error-handler'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from './components/react-dev-overlay/shared' import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from './components/react-dev-overlay/shared'
import { performFullReload } from './components/react-dev-overlay/pages/hot-reloader-client' import { performFullReload } from './components/react-dev-overlay/pages/hot-reloader-client'
import { initializeDevBuildIndicatorForPageRouter } from './dev/dev-build-indicator/initialize-for-page-router' import { initializeDevBuildIndicatorForPageRouter } from './dev/dev-build-indicator/initialize-for-page-router'
......
// This file is only used in app router due to the specific error state handling. // This file is only used in app router due to the specific error state handling.
import type { HydrationOptions } from 'react-dom/client' import type { HydrationOptions } from 'react-dom/client'
import { getReactStitchedError } from '../components/react-dev-overlay/internal/helpers/stitched-error' import { getReactStitchedError } from '../components/errors/stitched-error'
import { handleClientError } from '../components/react-dev-overlay/internal/helpers/use-error-handler' import { handleClientError } from '../components/errors/use-error-handler'
import { isNextRouterError } from '../components/is-next-router-error' import { isNextRouterError } from '../components/is-next-router-error'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { reportGlobalError } from './report-global-error' import { reportGlobalError } from './report-global-error'
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
import type { HydrationOptions } from 'react-dom/client' import type { HydrationOptions } from 'react-dom/client'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { reportGlobalError } from './report-global-error' import { reportGlobalError } from './report-global-error'
import { getReactStitchedError } from '../components/react-dev-overlay/internal/helpers/stitched-error' import { getReactStitchedError } from '../components/errors/stitched-error'
import isError from '../../lib/is-error' import isError from '../../lib/is-error'
export const onRecoverableError: HydrationOptions['onRecoverableError'] = ( export const onRecoverableError: HydrationOptions['onRecoverableError'] = (
......
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