Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 4 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions packages/next/src/client/components/app-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ import {
} from '../../shared/lib/hooks-client-context.shared-runtime'
import { useReducer, useUnwrapState } from './use-reducer'
import {
default as DefaultGlobalError,
ErrorBoundary,
type ErrorComponent,
type GlobalErrorComponent,
} from './error-boundary'
import { isBot } from '../../shared/lib/router/utils/is-bot'
Expand Down Expand Up @@ -617,6 +617,12 @@ function Router({
)

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') {
const { DevRootHTTPAccessFallbackBoundary } =
require('./dev-root-http-access-fallback-boundary') as typeof import('./dev-root-http-access-fallback-boundary')
Expand All @@ -634,6 +640,16 @@ function Router({
{content}
</HotReloader>
)
} else {
// In production, we only apply the user-customized global error boundary.
content = (
<ErrorBoundary
errorComponent={globalError[0]}
errorStyles={globalError[1]}
>
{content}
</ErrorBoundary>
)
}

return (
Expand Down Expand Up @@ -672,9 +688,9 @@ export default function AppRouter({

return (
<ErrorBoundary
// globalErrorComponent doesn't need `reset`, we do a type cast here to fit the ErrorBoundary type
errorComponent={globalErrorComponent as ErrorComponent}
errorStyles={globalErrorStyles}
// 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
actionQueue={actionQueue}
Expand Down
4 changes: 3 additions & 1 deletion packages/next/src/client/components/error-boundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ const styles = {

export type ErrorComponent = React.ComponentType<{
error: Error
reset: () => void
// global-error, there's no `reset` function;
// regular error boundary, there's a `reset` function.
reset?: () => void
}>

export interface ErrorBoundaryProps {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import type { GlobalErrorComponent } from '../../error-boundary'

import { PureComponent } from 'react'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import {
ErrorBoundary,
type GlobalErrorComponent,
GlobalError as DefaultGlobalError,
} from '../../error-boundary'

type AppDevOverlayErrorBoundaryProps = {
children: React.ReactNode
Expand Down Expand Up @@ -31,10 +34,10 @@ function ErroredHtml({
)
}
return (
<>
<ErrorBoundary errorComponent={DefaultGlobalError}>
{globalErrorStyles}
<GlobalError error={error} />
</>
</ErrorBoundary>
)
}

Expand Down
2 changes: 1 addition & 1 deletion test/e2e/app-dir/global-error/basic/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { assertHasRedbox, getRedboxDescription } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'

describe('app dir - global error', () => {
describe('app dir - global-error', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'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>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default function Layout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
10 changes: 10 additions & 0 deletions test/e2e/app-dir/global-error/error-in-global-error/app/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use client'

import { useEffect } from 'react'

export default function Page() {
useEffect(() => {
throw new Error('error in page')
}, [])
return <p>index page</p>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
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).toBe(
'Application error: a client-side exception has occurred while loading localhost (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)",
],
}
`)
}
})
})
Loading