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'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id'
import { isBot } from '../shared/lib/router/utils/is-bot'
/// <reference types="react-dom/experimental" />
......@@ -169,7 +168,6 @@ function ServerRoot({
const router = (
<AppRouter
gracefullyDegrade={isBot(window.navigator.userAgent)}
actionQueue={actionQueue}
globalErrorState={initialRSCPayload.G}
assetPrefix={initialRSCPayload.p}
......
......@@ -22,8 +22,6 @@ import {
PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime'
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 { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer'
......@@ -44,7 +42,8 @@ import {
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError, RedirectType } from './redirect-error'
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: {
pendingMpaPath?: string
......@@ -196,12 +195,10 @@ function Router({
actionQueue,
assetPrefix,
globalError,
gracefullyDegrade,
}: {
actionQueue: AppRouterActionQueue
assetPrefix: string
globalError: GlobalErrorState
gracefullyDegrade: boolean
}) {
const state = useActionQueue(actionQueue)
const { canonicalUrl } = state
......@@ -517,20 +514,14 @@ function Router({
</HotReloader>
)
} else {
// If gracefully degrading is applied in production,
// leave the app as it is rather than caught by GlobalError boundary.
if (gracefullyDegrade) {
content = <GracefulDegradeBoundary>{content}</GracefulDegradeBoundary>
} else {
content = (
<ErrorBoundary
errorComponent={globalError[0]}
errorStyles={globalError[1]}
>
{content}
</ErrorBoundary>
)
}
content = (
<RootErrorBoundary
errorComponent={globalError[0]}
errorStyles={globalError[1]}
>
{content}
</RootErrorBoundary>
)
}
return (
......@@ -565,12 +556,10 @@ export default function AppRouter({
actionQueue,
globalErrorState,
assetPrefix,
gracefullyDegrade,
}: {
actionQueue: AppRouterActionQueue
globalErrorState: GlobalErrorState
assetPrefix: string
gracefullyDegrade: boolean
}) {
useNavFailureHandler()
......@@ -579,23 +568,16 @@ export default function AppRouter({
actionQueue={actionQueue}
assetPrefix={assetPrefix}
globalError={globalErrorState}
gracefullyDegrade={gracefullyDegrade}
/>
)
if (gracefullyDegrade) {
return router
} else {
return (
<ErrorBoundary
// At the very top level, use the default GlobalError component as the final fallback.
// When the app router itself fails, which means the framework itself fails, we show the default error.
errorComponent={DefaultGlobalError}
>
{router}
</ErrorBoundary>
)
}
// At the very top level, use the default GlobalError component as the final fallback.
// When the app router itself fails, which means the framework itself fails, we show the default error.
return (
<RootErrorBoundary errorComponent={DefaultGlobalError}>
{router}
</RootErrorBoundary>
)
}
const runtimeStyles = new Set<string>()
......
......@@ -5,6 +5,10 @@ import { useUntrackedPathname } from './navigation-untracked'
import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler'
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<{
error: Error
......@@ -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.
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 (
<>
<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({
return <>{children}</>
}
function RenderChildren({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
/**
* 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.
......@@ -507,7 +503,6 @@ export default function OuterLayoutRouter({
notFound,
forbidden,
unauthorized,
gracefullyDegrade,
segmentViewBoundaries,
}: {
parallelRouterKey: string
......@@ -520,7 +515,6 @@ export default function OuterLayoutRouter({
notFound: React.ReactNode | undefined
forbidden: React.ReactNode | undefined
unauthorized: React.ReactNode | undefined
gracefullyDegrade?: boolean
segmentViewBoundaries?: React.ReactNode
}) {
const context = useContext(LayoutRouterContext)
......@@ -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.
*/
const ErrorBoundaryComponent = gracefullyDegrade
? RenderChildren
: ErrorBoundary
let segmentBoundaryTriggerNode: React.ReactNode = null
let segmentViewStateNode: React.ReactNode = null
if (
......@@ -651,7 +641,7 @@ export default function OuterLayoutRouter({
key={stateKey}
value={
<ScrollAndFocusHandler segmentPath={segmentPath}>
<ErrorBoundaryComponent
<ErrorBoundary
errorComponent={error}
errorStyles={errorStyles}
errorScripts={errorScripts}
......@@ -673,7 +663,7 @@ export default function OuterLayoutRouter({
</RedirectBoundary>
</HTTPAccessFallbackBoundary>
</LoadingBoundary>
</ErrorBoundaryComponent>
</ErrorBoundary>
{segmentViewStateNode}
</ScrollAndFocusHandler>
}
......
......@@ -1309,14 +1309,12 @@ function App<T>({
preinitScripts,
clientReferenceManifest,
ServerInsertedHTMLProvider,
gracefullyDegrade,
nonce,
}: {
reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string
}): JSX.Element {
preinitScripts()
......@@ -1360,7 +1358,6 @@ function App<T>({
actionQueue={actionQueue}
globalErrorState={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
</HeadManagerContext.Provider>
......@@ -1375,14 +1372,12 @@ function ErrorApp<T>({
preinitScripts,
clientReferenceManifest,
ServerInsertedHTMLProvider,
gracefullyDegrade,
nonce,
}: {
reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string
}): JSX.Element {
preinitScripts()
......@@ -1417,7 +1412,6 @@ function ErrorApp<T>({
actionQueue={actionQueue}
globalErrorState={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
)
......@@ -2070,7 +2064,6 @@ async function renderToStream(
const {
basePath,
botType,
buildManifest,
clientReferenceManifest,
ComponentMod,
......@@ -2289,7 +2282,6 @@ async function renderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
gracefullyDegrade={!!botType}
/>,
postponed,
{ onError: htmlRendererErrorHandler, nonce }
......@@ -2327,7 +2319,6 @@ async function renderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -2486,7 +2477,6 @@ async function renderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest}
gracefullyDegrade={!!botType}
nonce={nonce}
/>
),
......@@ -2585,7 +2575,7 @@ async function spawnDynamicValidationInDev(
workStore,
} = ctx
const { allowEmptyStaticShell = false, botType } = renderOpts
const { allowEmptyStaticShell = false } = renderOpts
// These values are placeholder values for this validating render
// that are provided during the actual prerenderToStream.
......@@ -2830,7 +2820,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -3059,7 +3048,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -3208,7 +3196,6 @@ async function prerenderToStream(
const {
allowEmptyStaticShell = false,
basePath,
botType,
buildManifest,
clientReferenceManifest,
ComponentMod,
......@@ -3573,7 +3560,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -3807,7 +3793,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -3965,7 +3950,6 @@ async function prerenderToStream(
preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
JSON.parse(JSON.stringify(postponed)),
......@@ -4071,7 +4055,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -4203,7 +4186,6 @@ async function prerenderToStream(
preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
JSON.parse(JSON.stringify(postponed)),
......@@ -4287,7 +4269,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
{
......@@ -4461,7 +4442,6 @@ async function prerenderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest}
gracefullyDegrade={!!botType}
nonce={nonce}
/>
),
......
......@@ -201,8 +201,6 @@ async function createComponentTreeInternal(
() => getLayoutOrPageModule(tree)
)
const gracefullyDegrade = !!ctx.renderOpts.botType
/**
* Checks if the current segment is a root layout.
*/
......@@ -647,9 +645,6 @@ async function createComponentTreeInternal(
forbidden={forbiddenComponent}
unauthorized={unauthorizedComponent}
{...(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,
]
......
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