Unverified Commit 7dccec01 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[global-error] fallback to default error when user one fails (#76339)

parent 69333f51
...@@ -41,8 +41,8 @@ import { ...@@ -41,8 +41,8 @@ import {
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { useReducer, useUnwrapState } from './use-reducer' import { useReducer, useUnwrapState } from './use-reducer'
import { import {
default as DefaultGlobalError,
ErrorBoundary, ErrorBoundary,
type ErrorComponent,
type GlobalErrorComponent, type GlobalErrorComponent,
} from './error-boundary' } from './error-boundary'
import { isBot } from '../../shared/lib/router/utils/is-bot' import { isBot } from '../../shared/lib/router/utils/is-bot'
...@@ -617,6 +617,12 @@ function Router({ ...@@ -617,6 +617,12 @@ function Router({
) )
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
// In development, we apply few error boundaries and hot-reloader:
// - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout
// - HotReloader:
// - hot-reload the app when the code changes
// - render dev overlay
// - catch runtime errors and display global-error when necessary
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const { DevRootHTTPAccessFallbackBoundary } = const { DevRootHTTPAccessFallbackBoundary } =
require('./dev-root-http-access-fallback-boundary') as typeof import('./dev-root-http-access-fallback-boundary') require('./dev-root-http-access-fallback-boundary') as typeof import('./dev-root-http-access-fallback-boundary')
...@@ -634,6 +640,16 @@ function Router({ ...@@ -634,6 +640,16 @@ function Router({
{content} {content}
</HotReloader> </HotReloader>
) )
} else {
// In production, we only apply the user-customized global error boundary.
content = (
<ErrorBoundary
errorComponent={globalError[0]}
errorStyles={globalError[1]}
>
{content}
</ErrorBoundary>
)
} }
return ( return (
...@@ -672,9 +688,9 @@ export default function AppRouter({ ...@@ -672,9 +688,9 @@ export default function AppRouter({
return ( return (
<ErrorBoundary <ErrorBoundary
// globalErrorComponent doesn't need `reset`, we do a type cast here to fit the ErrorBoundary type // At the very top level, use the default GlobalError component as the final fallback.
errorComponent={globalErrorComponent as ErrorComponent} // When the app router itself fails, which means the framework itself fails, we show the default error.
errorStyles={globalErrorStyles} errorComponent={DefaultGlobalError}
> >
<Router <Router
actionQueue={actionQueue} actionQueue={actionQueue}
......
...@@ -28,7 +28,9 @@ const styles = { ...@@ -28,7 +28,9 @@ const styles = {
export type ErrorComponent = React.ComponentType<{ export type ErrorComponent = React.ComponentType<{
error: Error error: Error
reset: () => void // global-error, there's no `reset` function;
// regular error boundary, there's a `reset` function.
reset?: () => void
}> }>
export interface ErrorBoundaryProps { export interface ErrorBoundaryProps {
......
import type { GlobalErrorComponent } from '../../error-boundary'
import { PureComponent } from 'react' import { PureComponent } from 'react'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import {
ErrorBoundary,
type GlobalErrorComponent,
GlobalError as DefaultGlobalError,
} from '../../error-boundary'
type AppDevOverlayErrorBoundaryProps = { type AppDevOverlayErrorBoundaryProps = {
children: React.ReactNode children: React.ReactNode
...@@ -30,10 +33,10 @@ function ErroredHtml({ ...@@ -30,10 +33,10 @@ function ErroredHtml({
) )
} }
return ( return (
<> <ErrorBoundary errorComponent={DefaultGlobalError}>
{globalErrorStyles} {globalErrorStyles}
<GlobalError error={error} /> <GlobalError error={error} />
</> </ErrorBoundary>
) )
} }
......
import { assertHasRedbox, getRedboxDescription } from 'next-test-utils' import { assertHasRedbox, getRedboxDescription } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('app dir - global error', () => { describe('app dir - global-error', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
'use client'
import { useRouter, useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
function InnerGlobalError({ error }) {
useRouter() // do nothing but ensure the call won't fail
const searchParams = useSearchParams()
if (searchParams.get('error-in-global-error') === '1') {
throw new Error('error in global error')
}
return (
<html>
<head></head>
<body>
<h1>Custom Global Error</h1>
</body>
</html>
)
}
export default function GlobalError({ error }) {
return (
<Suspense fallback={<p>Loading...</p>}>
<InnerGlobalError error={error} />
</Suspense>
)
}
export default function Layout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
'use client'
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
throw new Error('error in page')
}, [])
return <p>index page</p>
}
import { nextTestSetup } from 'e2e-utils'
import { assertHasRedbox } from 'next-test-utils'
describe('app dir - global-error - error-in-global-error', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('should be able to use nextjs navigation hook in global-error', async () => {
const browser = await next.browser('/')
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Custom Global Error')
if (isNextDev) {
await assertHasRedbox(browser)
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: error in page",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": "app/page.js (7:11) @ Page.useEffect
> 7 | throw new Error('error in page')
| ^",
"stack": [
"Page.useEffect app/page.js (7:11)",
],
}
`)
}
})
it('should render fallback UI when error occurs in global-error', async () => {
const browser = await next.browser('/?error-in-global-error=1')
const text = await browser.elementByCss('h2').text()
expect(text).toMatch(
/Application error: a client-side exception has occurred while loading [\w.-]+ \(see the browser console for more information\)./
)
if (isNextDev) {
await assertHasRedbox(browser)
await expect(browser).toDisplayRedbox(`
{
"count": 2,
"description": "Error: error in global error",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": "app/global-error.js (10:11) @ InnerGlobalError
> 10 | throw new Error('error in global error')
| ^",
"stack": [
"InnerGlobalError app/global-error.js (10:11)",
"GlobalError app/global-error.js (26:7)",
],
}
`)
}
})
})
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