Unverified Commit dcece129 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[errors] revamp graceful degrade error boundary (#82474)

parent e30dd09f
...@@ -21,7 +21,6 @@ import type { InitialRSCPayload } from '../server/app-render/types' ...@@ -21,7 +21,6 @@ import type { InitialRSCPayload } from '../server/app-render/types'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state' import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime' import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id' import { setAppBuildId } from './app-build-id'
import { isBot } from '../shared/lib/router/utils/is-bot'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -169,7 +168,6 @@ function ServerRoot({ ...@@ -169,7 +168,6 @@ function ServerRoot({
const router = ( const router = (
<AppRouter <AppRouter
gracefullyDegrade={isBot(window.navigator.userAgent)}
actionQueue={actionQueue} actionQueue={actionQueue}
globalErrorState={initialRSCPayload.G} globalErrorState={initialRSCPayload.G}
assetPrefix={initialRSCPayload.p} assetPrefix={initialRSCPayload.p}
......
...@@ -22,8 +22,6 @@ import { ...@@ -22,8 +22,6 @@ import {
PathParamsContext, PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { dispatchAppRouterAction, useActionQueue } from './use-action-queue' import { dispatchAppRouterAction, useActionQueue } from './use-action-queue'
import { ErrorBoundary } from './error-boundary'
import DefaultGlobalError from './builtin/global-error'
import { isBot } from '../../shared/lib/router/utils/is-bot' import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
...@@ -44,7 +42,8 @@ import { ...@@ -44,7 +42,8 @@ import {
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError, RedirectType } from './redirect-error' import { isRedirectError, RedirectType } from './redirect-error'
import { pingVisibleLinks } from './links' import { pingVisibleLinks } from './links'
import GracefulDegradeBoundary from './errors/graceful-degrade-boundary' import RootErrorBoundary from './errors/root-error-boundary'
import DefaultGlobalError from './builtin/global-error'
const globalMutable: { const globalMutable: {
pendingMpaPath?: string pendingMpaPath?: string
...@@ -196,12 +195,10 @@ function Router({ ...@@ -196,12 +195,10 @@ function Router({
actionQueue, actionQueue,
assetPrefix, assetPrefix,
globalError, globalError,
gracefullyDegrade,
}: { }: {
actionQueue: AppRouterActionQueue actionQueue: AppRouterActionQueue
assetPrefix: string assetPrefix: string
globalError: GlobalErrorState globalError: GlobalErrorState
gracefullyDegrade: boolean
}) { }) {
const state = useActionQueue(actionQueue) const state = useActionQueue(actionQueue)
const { canonicalUrl } = state const { canonicalUrl } = state
...@@ -517,20 +514,14 @@ function Router({ ...@@ -517,20 +514,14 @@ function Router({
</HotReloader> </HotReloader>
) )
} else { } else {
// If gracefully degrading is applied in production, content = (
// leave the app as it is rather than caught by GlobalError boundary. <RootErrorBoundary
if (gracefullyDegrade) { errorComponent={globalError[0]}
content = <GracefulDegradeBoundary>{content}</GracefulDegradeBoundary> errorStyles={globalError[1]}
} else { >
content = ( {content}
<ErrorBoundary </RootErrorBoundary>
errorComponent={globalError[0]} )
errorStyles={globalError[1]}
>
{content}
</ErrorBoundary>
)
}
} }
return ( return (
...@@ -565,12 +556,10 @@ export default function AppRouter({ ...@@ -565,12 +556,10 @@ export default function AppRouter({
actionQueue, actionQueue,
globalErrorState, globalErrorState,
assetPrefix, assetPrefix,
gracefullyDegrade,
}: { }: {
actionQueue: AppRouterActionQueue actionQueue: AppRouterActionQueue
globalErrorState: GlobalErrorState globalErrorState: GlobalErrorState
assetPrefix: string assetPrefix: string
gracefullyDegrade: boolean
}) { }) {
useNavFailureHandler() useNavFailureHandler()
...@@ -579,23 +568,16 @@ export default function AppRouter({ ...@@ -579,23 +568,16 @@ export default function AppRouter({
actionQueue={actionQueue} actionQueue={actionQueue}
assetPrefix={assetPrefix} assetPrefix={assetPrefix}
globalError={globalErrorState} globalError={globalErrorState}
gracefullyDegrade={gracefullyDegrade}
/> />
) )
if (gracefullyDegrade) { // At the very top level, use the default GlobalError component as the final fallback.
return router // When the app router itself fails, which means the framework itself fails, we show the default error.
} else { return (
return ( <RootErrorBoundary errorComponent={DefaultGlobalError}>
<ErrorBoundary {router}
// At the very top level, use the default GlobalError component as the final fallback. </RootErrorBoundary>
// When the app router itself fails, which means the framework itself fails, we show the default error. )
errorComponent={DefaultGlobalError}
>
{router}
</ErrorBoundary>
)
}
} }
const runtimeStyles = new Set<string>() const runtimeStyles = new Set<string>()
......
...@@ -5,6 +5,10 @@ import { useUntrackedPathname } from './navigation-untracked' ...@@ -5,6 +5,10 @@ import { useUntrackedPathname } from './navigation-untracked'
import { isNextRouterError } from './is-next-router-error' import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler' import { handleHardNavError } from './nav-failure-handler'
import { HandleISRError } from './handle-isr-error' import { HandleISRError } from './handle-isr-error'
import { isBot } from '../../shared/lib/router/utils/is-bot'
const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent)
export type ErrorComponent = React.ComponentType<{ export type ErrorComponent = React.ComponentType<{
error: Error error: Error
...@@ -93,7 +97,9 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -93,7 +97,9 @@ export class ErrorBoundaryHandler extends React.Component<
// Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version. // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.
render(): React.ReactNode { render(): React.ReactNode {
if (this.state.error) { //When it's bot request, segment level error boundary will keep rendering the children,
// the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.
if (this.state.error && !isBotUserAgent) {
return ( return (
<> <>
<HandleISRError error={this.state.error} /> <HandleISRError error={this.state.error} />
......
'use client'
import React, { type JSX } from 'react'
import GracefulDegradeBoundary from './graceful-degrade-boundary'
import { ErrorBoundary, type ErrorBoundaryProps } from '../error-boundary'
import { isBot } from '../../../shared/lib/router/utils/is-bot'
const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent)
export default function RootErrorBoundary({
children,
errorComponent,
errorStyles,
errorScripts,
}: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element {
if (isBotUserAgent) {
// Preserve existing DOM/HTML for bots to avoid replacing content with an error UI
// and to keep the original SSR output intact.
return <GracefulDegradeBoundary>{children}</GracefulDegradeBoundary>
}
return (
<ErrorBoundary
errorComponent={errorComponent}
errorStyles={errorStyles}
errorScripts={errorScripts}
>
{children}
</ErrorBoundary>
)
}
...@@ -488,10 +488,6 @@ function LoadingBoundary({ ...@@ -488,10 +488,6 @@ function LoadingBoundary({
return <>{children}</> return <>{children}</>
} }
function RenderChildren({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
/** /**
* OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments. * OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.
* It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes. * It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.
...@@ -507,7 +503,6 @@ export default function OuterLayoutRouter({ ...@@ -507,7 +503,6 @@ export default function OuterLayoutRouter({
notFound, notFound,
forbidden, forbidden,
unauthorized, unauthorized,
gracefullyDegrade,
segmentViewBoundaries, segmentViewBoundaries,
}: { }: {
parallelRouterKey: string parallelRouterKey: string
...@@ -520,7 +515,6 @@ export default function OuterLayoutRouter({ ...@@ -520,7 +515,6 @@ export default function OuterLayoutRouter({
notFound: React.ReactNode | undefined notFound: React.ReactNode | undefined
forbidden: React.ReactNode | undefined forbidden: React.ReactNode | undefined
unauthorized: React.ReactNode | undefined unauthorized: React.ReactNode | undefined
gracefullyDegrade?: boolean
segmentViewBoundaries?: React.ReactNode segmentViewBoundaries?: React.ReactNode
}) { }) {
const context = useContext(LayoutRouterContext) const context = useContext(LayoutRouterContext)
...@@ -612,10 +606,6 @@ export default function OuterLayoutRouter({ ...@@ -612,10 +606,6 @@ export default function OuterLayoutRouter({
- Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch. - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.
*/ */
const ErrorBoundaryComponent = gracefullyDegrade
? RenderChildren
: ErrorBoundary
let segmentBoundaryTriggerNode: React.ReactNode = null let segmentBoundaryTriggerNode: React.ReactNode = null
let segmentViewStateNode: React.ReactNode = null let segmentViewStateNode: React.ReactNode = null
if ( if (
...@@ -651,7 +641,7 @@ export default function OuterLayoutRouter({ ...@@ -651,7 +641,7 @@ export default function OuterLayoutRouter({
key={stateKey} key={stateKey}
value={ value={
<ScrollAndFocusHandler segmentPath={segmentPath}> <ScrollAndFocusHandler segmentPath={segmentPath}>
<ErrorBoundaryComponent <ErrorBoundary
errorComponent={error} errorComponent={error}
errorStyles={errorStyles} errorStyles={errorStyles}
errorScripts={errorScripts} errorScripts={errorScripts}
...@@ -673,7 +663,7 @@ export default function OuterLayoutRouter({ ...@@ -673,7 +663,7 @@ export default function OuterLayoutRouter({
</RedirectBoundary> </RedirectBoundary>
</HTTPAccessFallbackBoundary> </HTTPAccessFallbackBoundary>
</LoadingBoundary> </LoadingBoundary>
</ErrorBoundaryComponent> </ErrorBoundary>
{segmentViewStateNode} {segmentViewStateNode}
</ScrollAndFocusHandler> </ScrollAndFocusHandler>
} }
......
...@@ -1309,14 +1309,12 @@ function App<T>({ ...@@ -1309,14 +1309,12 @@ function App<T>({
preinitScripts, preinitScripts,
clientReferenceManifest, clientReferenceManifest,
ServerInsertedHTMLProvider, ServerInsertedHTMLProvider,
gracefullyDegrade,
nonce, nonce,
}: { }: {
reactServerStream: BinaryStreamOf<T> reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }> ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string nonce?: string
}): JSX.Element { }): JSX.Element {
preinitScripts() preinitScripts()
...@@ -1360,7 +1358,6 @@ function App<T>({ ...@@ -1360,7 +1358,6 @@ function App<T>({
actionQueue={actionQueue} actionQueue={actionQueue}
globalErrorState={response.G} globalErrorState={response.G}
assetPrefix={response.p} assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/> />
</ServerInsertedHTMLProvider> </ServerInsertedHTMLProvider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
...@@ -1375,14 +1372,12 @@ function ErrorApp<T>({ ...@@ -1375,14 +1372,12 @@ function ErrorApp<T>({
preinitScripts, preinitScripts,
clientReferenceManifest, clientReferenceManifest,
ServerInsertedHTMLProvider, ServerInsertedHTMLProvider,
gracefullyDegrade,
nonce, nonce,
}: { }: {
reactServerStream: BinaryStreamOf<T> reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }> ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string nonce?: string
}): JSX.Element { }): JSX.Element {
preinitScripts() preinitScripts()
...@@ -1417,7 +1412,6 @@ function ErrorApp<T>({ ...@@ -1417,7 +1412,6 @@ function ErrorApp<T>({
actionQueue={actionQueue} actionQueue={actionQueue}
globalErrorState={response.G} globalErrorState={response.G}
assetPrefix={response.p} assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/> />
</ServerInsertedHTMLProvider> </ServerInsertedHTMLProvider>
) )
...@@ -2070,7 +2064,6 @@ async function renderToStream( ...@@ -2070,7 +2064,6 @@ async function renderToStream(
const { const {
basePath, basePath,
botType,
buildManifest, buildManifest,
clientReferenceManifest, clientReferenceManifest,
ComponentMod, ComponentMod,
...@@ -2289,7 +2282,6 @@ async function renderToStream( ...@@ -2289,7 +2282,6 @@ async function renderToStream(
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce} nonce={nonce}
gracefullyDegrade={!!botType}
/>, />,
postponed, postponed,
{ onError: htmlRendererErrorHandler, nonce } { onError: htmlRendererErrorHandler, nonce }
...@@ -2327,7 +2319,6 @@ async function renderToStream( ...@@ -2327,7 +2319,6 @@ async function renderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -2486,7 +2477,6 @@ async function renderToStream( ...@@ -2486,7 +2477,6 @@ async function renderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts} preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/> />
), ),
...@@ -2585,7 +2575,7 @@ async function spawnDynamicValidationInDev( ...@@ -2585,7 +2575,7 @@ async function spawnDynamicValidationInDev(
workStore, workStore,
} = ctx } = ctx
const { allowEmptyStaticShell = false, botType } = renderOpts const { allowEmptyStaticShell = false } = renderOpts
// These values are placeholder values for this validating render // These values are placeholder values for this validating render
// that are provided during the actual prerenderToStream. // that are provided during the actual prerenderToStream.
...@@ -2830,7 +2820,6 @@ async function spawnDynamicValidationInDev( ...@@ -2830,7 +2820,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -3059,7 +3048,6 @@ async function spawnDynamicValidationInDev( ...@@ -3059,7 +3048,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -3208,7 +3196,6 @@ async function prerenderToStream( ...@@ -3208,7 +3196,6 @@ async function prerenderToStream(
const { const {
allowEmptyStaticShell = false, allowEmptyStaticShell = false,
basePath, basePath,
botType,
buildManifest, buildManifest,
clientReferenceManifest, clientReferenceManifest,
ComponentMod, ComponentMod,
...@@ -3573,7 +3560,6 @@ async function prerenderToStream( ...@@ -3573,7 +3560,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -3807,7 +3793,6 @@ async function prerenderToStream( ...@@ -3807,7 +3793,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -3965,7 +3950,6 @@ async function prerenderToStream( ...@@ -3965,7 +3950,6 @@ async function prerenderToStream(
preinitScripts={() => {}} preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
JSON.parse(JSON.stringify(postponed)), JSON.parse(JSON.stringify(postponed)),
...@@ -4071,7 +4055,6 @@ async function prerenderToStream( ...@@ -4071,7 +4055,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -4203,7 +4186,6 @@ async function prerenderToStream( ...@@ -4203,7 +4186,6 @@ async function prerenderToStream(
preinitScripts={() => {}} preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
JSON.parse(JSON.stringify(postponed)), JSON.parse(JSON.stringify(postponed)),
...@@ -4287,7 +4269,6 @@ async function prerenderToStream( ...@@ -4287,7 +4269,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
{ {
...@@ -4461,7 +4442,6 @@ async function prerenderToStream( ...@@ -4461,7 +4442,6 @@ async function prerenderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts} preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/> />
), ),
......
...@@ -201,8 +201,6 @@ async function createComponentTreeInternal( ...@@ -201,8 +201,6 @@ async function createComponentTreeInternal(
() => getLayoutOrPageModule(tree) () => getLayoutOrPageModule(tree)
) )
const gracefullyDegrade = !!ctx.renderOpts.botType
/** /**
* Checks if the current segment is a root layout. * Checks if the current segment is a root layout.
*/ */
...@@ -647,9 +645,6 @@ async function createComponentTreeInternal( ...@@ -647,9 +645,6 @@ async function createComponentTreeInternal(
forbidden={forbiddenComponent} forbidden={forbiddenComponent}
unauthorized={unauthorizedComponent} unauthorized={unauthorizedComponent}
{...(isSegmentViewEnabled && { segmentViewBoundaries })} {...(isSegmentViewEnabled && { segmentViewBoundaries })}
// Since gracefullyDegrade only applies to bots, only
// pass it when we're in a bot context to avoid extra bytes.
{...(gracefullyDegrade && { gracefullyDegrade })}
/>, />,
childCacheNodeSeedData, childCacheNodeSeedData,
] ]
......
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