Unverified Commit fa32daad authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Add `unstable_catchError()` API for custom error boundary (#89688)

This PR adds `unstable_catchError()` API for a granular custom error
boundary. The error component generated by this API is not a true
component format, as the wrapper provides additional args. Therefore,
the API is a function call by design rather than a boundary component to
avoid merging the `errorInfo` with the user-provided props from the
wrapper.

This API works for both the App/Pages Router. However, `retry()` is not
allowed in Pages Router as it depends on `router.refresh()`, and will
throw. Also, it's exported from `next/error` as there was already an
`Error` component for the [Pages
Router](https://nextjs.org/docs/pages/building-your-application/routing/custom-error#reusing-the-built-in-error-page).

### DevTools

<img width="508" height="90" alt="CleanShot 2026-03-13 at 03 02 46@2x"
src="https://github.com/user-attachments/assets/8b79b1f6-877d-4901-99f7-6a2b4d3e34fe"
/>

Docs to follow up: https://github.com/vercel/next.js/pull/89847
Closes NAR-768

---------
Co-authored-by: 's avatarJosh Story <story@hey.com>
parent 672b02b2
......@@ -71,7 +71,16 @@ pub async fn get_next_client_import_map(
.await?;
match &ty {
ClientContextType::Pages { .. } => {}
ClientContextType::Pages { .. } => {
// Resolve next/error to the ESM entry point so the bundler can
// tree-shake the error-boundary dependency chain from Pages
// Router bundles that only use the default Error component.
insert_exact_alias_or_js(
&mut import_map,
rcstr!("next/error"),
request_to_import_mapping(project_path.clone(), rcstr!("next/dist/api/error")),
);
}
ClientContextType::App { app_dir } => {
// Keep in sync with file:///./../../../packages/next/src/lib/needs-experimental-react.ts
let taint = *next_config.enable_taint().await?;
......@@ -404,6 +413,7 @@ pub async fn get_next_edge_import_map(
rcstr!("next/app") => rcstr!("next/dist/api/app"),
rcstr!("next/document") => rcstr!("next/dist/api/document"),
rcstr!("next/dynamic") => rcstr!("next/dist/api/dynamic"),
rcstr!("next/error") => rcstr!("next/dist/api/error"),
rcstr!("next/form") => rcstr!("next/dist/api/form"),
rcstr!("next/head") => rcstr!("next/dist/api/head"),
rcstr!("next/headers") => rcstr!("next/dist/api/headers"),
......@@ -953,6 +963,7 @@ async fn apply_vendored_react_aliases_server(
if react_condition == "server" {
// This is used in the server runtime to import React Server Components.
alias.extend(fxindexmap! {
rcstr!("next/error") => rcstr!("next/dist/api/error.react-server"),
rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"),
rcstr!("next/link") => rcstr!("next/dist/client/app-dir/link.react-server"),
});
......@@ -983,6 +994,7 @@ async fn rsc_aliases(
if ty.should_use_react_server_condition() {
// This is used in the server runtime to import React Server Components.
alias.extend(fxindexmap! {
rcstr!("next/error") => rcstr!("next/dist/api/error.react-server"),
rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"),
rcstr!("next/link") => rcstr!("next/dist/client/app-dir/link.react-server"),
});
......
......@@ -298,7 +298,7 @@ async fn get_pages_structure_for_root_directory(
PagesStructureItem::new(
pages_path.join("_error")?,
page_extensions,
Some(next_package.join("error.js")?),
Some(next_package.join("dist/pages/_error.js")?),
error_router_path.clone(),
error_router_path,
)
......
......@@ -678,6 +678,7 @@ impl ReactServerComponentValidator {
"useFormState",
],
),
(atom!("next/error").into(), vec!["unstable_catchError"]),
(
atom!("next/navigation").into(),
vec![
......
import Error from './dist/pages/_error'
export * from './dist/pages/_error'
import Error from './dist/api/error'
export * from './dist/api/error'
export default Error
module.exports = require('./dist/pages/_error')
// Keep the catch-error graph lazy so default Error consumers do not load it.
Object.defineProperty(module.exports, 'unstable_catchError', {
enumerable: true,
get() {
return require('./dist/client/components/catch-error').unstable_catchError
},
})
......@@ -1135,5 +1135,7 @@
"1134": "Route %s used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1135": "\"use cache\" cannot be used outside of App Router. Expected a WorkUnitStore.",
"1136": "Page \"%s\" cannot use both \\`export const unstable_dynamicStaleTime\\` and \\`export const unstable_instant\\`.",
"1137": "\"%s\" cannot use \\`export const unstable_dynamicStaleTime\\`. This config is only supported in page files, not layouts."
"1137": "\"%s\" cannot use \\`export const unstable_dynamicStaleTime\\`. This config is only supported in page files, not layouts.",
"1138": "`unstable_retry()` can only be used in the App Router. Use `reset()` in the Pages Router.",
"1139": "`unstable_catchError` can only be used in Client Components."
}
export function unstable_catchError(): never {
throw new Error(
'`unstable_catchError` can only be used in Client Components.'
)
}
export type { ErrorInfo } from '../client/components/error-boundary'
// Pages Router only
export { default } from '../pages/_error'
export * from '../pages/_error'
export { unstable_catchError } from '../client/components/catch-error'
export type { ErrorInfo } from '../client/components/error-boundary'
......@@ -202,6 +202,7 @@ export function createServerOnlyClientOnlyAliases(
export function createNextApiEsmAliases() {
const mapping = {
error: 'next/dist/api/error',
head: 'next/dist/api/head',
image: 'next/dist/api/image',
constants: 'next/dist/api/constants',
......@@ -237,6 +238,7 @@ export function createAppRouterApiAliases(isServerOnlyLayer: boolean) {
}
if (isServerOnlyLayer) {
mapping['error'] = 'next/dist/api/error.react-server'
mapping['navigation'] = 'next/dist/api/navigation.react-server'
mapping['link'] = 'next/dist/client/app-dir/link.react-server'
}
......
'use client'
import React from 'react'
import { HandleISRError } from '../handle-isr-error'
import { handleISRError } from '../handle-isr-error'
import { errorStyles, errorThemeCss, WarningIcon } from './error-styles'
export type GlobalErrorComponent = React.ComponentType<{
......@@ -18,13 +18,14 @@ function DefaultGlobalError({ error }: { error: any }) {
? 'A server error occurred. Reload to try again.'
: 'Reload to try again, or go back.'
handleISRError({ error })
return (
<html id="__next_error__">
<head>
<style dangerouslySetInnerHTML={{ __html: errorThemeCss }} />
</head>
<body>
<HandleISRError error={error} />
<div style={errorStyles.container}>
<div style={errorStyles.card}>
<WarningIcon />
......
'use client'
import type { ErrorInfo } from './error-boundary'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import React, { startTransition, useContext } from 'react'
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'
import { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime'
import { RouterContext as PagesRouterContext } from '../../shared/lib/router-context.shared-runtime'
const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent)
type UserProps = Record<string, any>
type CatchErrorProps<P extends UserProps> = {
pathname: string | null
isPagesRouter: boolean
fallback: React.ComponentType<{
props: Omit<P, 'children'>
errorInfo: ErrorInfo
}>
props: Omit<P, 'children'>
children: React.ReactNode
}
type CatchErrorState = {
error: Error | null
previousPathname: string | null
}
// This is forked from error-boundary.
// TODO: Extend it instead of forking to easily sync the behavior?
class CatchError<P extends UserProps> extends React.Component<
CatchErrorProps<P>,
{ error: Error | null; previousPathname: string | null }
> {
declare context: AppRouterInstance | null
static contextType = AppRouterContext
// `unstable_catchError()` is parsed as an HOC-style name and displays as
// a label (<name> [unstable_catchError]) in DevTools.
static displayName = 'unstable_catchError(Next.CatchError)'
constructor(props: CatchErrorProps<P>) {
super(props)
this.state = {
error: null,
previousPathname: this.props.pathname,
}
}
static getDerivedStateFromError(error: Error) {
if (isNextRouterError(error)) {
// Re-throw if an expected internal Next.js router error occurs
// this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)
throw error
}
return { error }
}
static getDerivedStateFromProps(
props: CatchErrorProps<UserProps>,
state: CatchErrorState
): CatchErrorState | null {
const { error } = state
// if we encounter an error while
// a navigation is pending we shouldn't render
// the error boundary and instead should fallback
// to a hard navigation to attempt recovering
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
if (error && handleHardNavError(error)) {
// clear error so we don't render anything
return {
error: null,
previousPathname: props.pathname,
}
}
}
/**
* Handles reset of the error boundary when a navigation happens.
* Ensures the error boundary does not stay enabled when navigating to a new page.
* Approach of setState in render is safe as it checks the previous pathname and then overrides
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders
*/
if (props.pathname !== state.previousPathname && state.error) {
return {
error: null,
previousPathname: props.pathname,
}
}
return {
error: state.error,
previousPathname: props.pathname,
}
}
reset = () => {
this.setState({ error: null })
}
unstable_retry = () => {
if (this.props.isPagesRouter) {
throw new Error(
'`unstable_retry()` can only be used in the App Router. Use `reset()` in the Pages Router.'
)
}
startTransition(() => {
this.context?.refresh()
this.reset()
})
}
// 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 {
//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) {
handleISRError({ error: this.state.error })
return (
<this.props.fallback
props={this.props.props}
errorInfo={{
error: this.state.error,
reset: this.reset,
unstable_retry: this.unstable_retry,
}}
/>
)
}
return this.props.children
}
}
/**
* `unstable_catchError` is a counterpart to `error.js` that provides a granular
* control of error boundaries at the component level. It provides the `ErrorInfo`
* including `unstable_retry` for error recovery.
*
* Pass a Component-like fallback function that receives the props and `ErrorInfo`.
* The props omit `children` intentionally as it is the "fallback" of the error and
* is not expected to render the children.
*
* This API is must be used inside the client module graph and cannot be imported
* in `server-only` environments like proxy, instrumentation, etc.
*
* @example
* ```tsx
* // CustomErrorBoundary.tsx
* 'use client'
* import { unstable_catchError, type ErrorInfo } from 'next/error'
*
* function CustomErrorBoundary(props: Props, errorInfo: ErrorInfo) {
* return ...
* }
*
* export default unstable_catchError(CustomErrorBoundary)
*
* // page.tsx
* 'use client'
* import CustomErrorBoundary from './CustomErrorBoundary'
*
* export default function Page() {
* return (
* <CustomErrorBoundary>
* ...
* </CustomErrorBoundary>
* )
* }
* ```
*/
export function unstable_catchError<P extends UserProps>(
fallback: (
// children is omitted by design as the error fallback component is the "fallback"
// for the children when an error occurs.
props: Omit<P, 'children'>,
errorInfo: ErrorInfo
) => React.ReactNode
): React.ComponentType<P> {
// Create Fallback component from the closure of `unstable_catchError`.
const Fallback = ({
props,
errorInfo,
}: {
props: Omit<P, 'children'>
errorInfo: ErrorInfo
}) => fallback(props, errorInfo)
// Rename to match the user component name for DevTools.
Fallback.displayName = fallback.name || 'CatchErrorFallback'
return ({ children, ...props }: P) => {
// When we're rendering the missing params shell, this will return null. This
// is because we won't be rendering any not found boundaries or error
// boundaries for the missing params shell. When this runs on the client
// (where these errors can occur), we will get the correct pathname.
const pathname = useUntrackedPathname()
const isPagesRouter = useContext(PagesRouterContext) !== null
return (
<CatchError
pathname={pathname}
isPagesRouter={isPagesRouter}
fallback={Fallback}
props={props}
>
{children}
</CatchError>
)
}
}
......@@ -4,7 +4,7 @@ import React, { startTransition, type JSX } from 'react'
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 { handleISRError } from './handle-isr-error'
import { isBot } from '../../shared/lib/router/utils/is-bot'
import {
AppRouterContext,
......@@ -14,11 +14,13 @@ import {
const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent)
export type ErrorComponent = React.ComponentType<{
export type ErrorInfo = {
error: Error
reset: () => void
unstable_retry: () => void
}>
}
export type ErrorComponent = React.ComponentType<ErrorInfo>
export interface ErrorBoundaryProps {
children?: React.ReactNode
......@@ -116,9 +118,10 @@ export class ErrorBoundaryHandler extends React.Component<
//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) {
handleISRError({ error: this.state.error })
return (
<>
<HandleISRError error={this.state.error} />
{this.props.errorStyles}
{this.props.errorScripts}
<this.props.errorComponent
......@@ -156,6 +159,7 @@ export function ErrorBoundary({
// boundaries for the missing params shell. When this runs on the client
// (where these errors can occur), we will get the correct pathname.
const pathname = useUntrackedPathname()
if (errorComponent) {
return (
<ErrorBoundaryHandler
......
......@@ -8,7 +8,7 @@ const workAsyncStorage =
// if we are revalidating we want to re-throw the error so the
// function crashes so we can maintain our previous cache
// instead of caching the error page
export function HandleISRError({ error }: { error: any }) {
export function handleISRError({ error }: { error: any }) {
if (workAsyncStorage) {
const store = workAsyncStorage.getStore()
if (store?.isStaticGeneration) {
......@@ -18,6 +18,4 @@ export function HandleISRError({ error }: { error: any }) {
throw error
}
}
return null
}
......@@ -256,6 +256,66 @@ describe('Error overlay - RSC build errors', () => {
})
}
it('should error when unstable_catchError from next/error is used in a server component', async () => {
await using sandbox = await createSandbox(
next,
new Map([
[
'app/page.js',
outdent`
import { unstable_catchError } from 'next/error'
export default function Page() {
return 'Hello world'
}
`,
],
])
)
const { session } = sandbox
await session.waitForRedbox()
expect(await session.getRedboxSource()).toInclude(
'You\'re importing a component that needs `unstable_catchError`. This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the `"use client"` directive.'
)
})
test.each([
['middleware.js', 'export function middleware() {}'],
['proxy.js', 'export function proxy() {}'],
['instrumentation.js', 'export function register() {}'],
])(
'should error when unstable_catchError from next/error is imported in %s',
async (entryFile, exportCode) => {
await using sandbox = await createSandbox(
next,
new Map([
[
'app/page.js',
outdent`
export default function Page() {
return 'Hello world'
}
`,
],
[
entryFile,
outdent`
import { unstable_catchError } from 'next/error'
${exportCode}
`,
],
])
)
const { session } = sandbox
await session.waitForRedbox()
expect(await session.getRedboxSource()).toInclude(
'You\'re importing a component that needs `unstable_catchError`. This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the `"use client"` directive.'
)
}
)
it('should allow to use and handle rsc poisoning server-only', async () => {
await using sandbox = await createSandbox(
next,
......
'use client'
import type { ErrorInfo } from 'next/error'
import { unstable_catchError } from 'next/error'
export function ErrorFallback(
props: { title: string },
{ error, reset, unstable_retry }: ErrorInfo
) {
return (
<>
<p id="error-boundary-message">{error.message}</p>
<p id="error-boundary-title">{props.title}</p>
<button id="reset" onClick={() => reset()}>
Reset
</button>
<button id="retry" onClick={() => unstable_retry()}>
Retry
</button>
</>
)
}
export default unstable_catchError(ErrorFallback)
import ErrorWrapper from './catch-error-wrapper'
export default function Layout({ children }: { children: React.ReactNode }) {
return <ErrorWrapper title="client-catch-error">{children}</ErrorWrapper>
}
'use client'
import { useState } from 'react'
export default function Page() {
const [clicked, setClicked] = useState(false)
if (clicked) {
throw new Error('this is a test')
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
'use client'
import type { ErrorInfo } from 'next/error'
import { unstable_catchError } from 'next/error'
export function ErrorFallback(
props: { title: string },
{ error, reset, unstable_retry }: ErrorInfo
) {
return (
<>
<p id="error-boundary-message">{error.message}</p>
<p id="error-boundary-title">{props.title}</p>
<button id="reset" onClick={() => reset()}>
Reset
</button>
<button id="retry" onClick={() => unstable_retry()}>
Retry
</button>
</>
)
}
export default unstable_catchError(ErrorFallback)
import ErrorWrapper from './catch-error-wrapper'
export default function Layout({ children }: { children: React.ReactNode }) {
// A prop can be passed from the RSC to the error component
const title = 'server-catch-error'
return <ErrorWrapper title={title}>{children}</ErrorWrapper>
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export default function Page() {
return (
<Suspense>
<PageImpl />
</Suspense>
)
}
let hasThrown = false
async function PageImpl() {
await connection()
if (!hasThrown) {
hasThrown = true
throw new Error('this is a test')
}
return <p id="recover">Recovered</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('app-dir - unstable_catchError with react compiler', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
nextConfig: {
reactCompiler: true,
},
dependencies: {
'babel-plugin-react-compiler': 'latest',
},
})
it('should recover Client Component error after reset', async () => {
const browser = await next.browser('/client-component')
// Try triggering and resetting a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigger-button')
.click()
.waitForElementByCss('#error-boundary-message')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
'this is a test'
)
await browser
.elementByCss('#reset')
.click()
.waitForElementByCss('#error-trigger-button')
expect(await browser.elementByCss('#error-trigger-button').text()).toBe(
'Trigger Error!'
)
}
})
it('should recover Client Component error after unstable_retry', async () => {
const browser = await next.browser('/client-component')
// Try triggering and retrying a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigger-button')
.click()
.waitForElementByCss('#error-boundary-message')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
'this is a test'
)
await browser
.elementByCss('#retry')
.click()
.waitForElementByCss('#error-trigger-button')
expect(await browser.elementByCss('#error-trigger-button').text()).toBe(
'Trigger Error!'
)
}
})
it('should recover Server Component error after unstable_retry', async () => {
const browser = await next.browser('/server-component')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
isNextDev
? 'this is a test'
: 'An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.'
)
await browser.elementByCss('#retry').click().waitForElementByCss('#recover')
expect(await browser.elementByCss('#recover').text()).toBe('Recovered')
})
it('should recover after reset on Pages Router', async () => {
const browser = await next.browser('/pages-router')
await browser
.elementByCss('#pages-trigger')
.click()
.waitForElementByCss('#pages-error-message')
expect(await browser.elementByCss('#pages-error-message').text()).toBe(
'this is a pages test'
)
await browser.eval(`document.getElementById('pages-reset')?.click()`)
await browser.waitForElementByCss('#pages-trigger')
expect(await browser.elementByCss('#pages-trigger').text()).toBe(
'Trigger Error!'
)
})
it('should throw when unstable_retry is called on Pages Router', async () => {
const browser = await next.browser('/pages-router')
await browser
.elementByCss('#pages-trigger')
.click()
.waitForElementByCss('#pages-error-message')
await browser.eval(`document.getElementById('pages-retry')?.click()`)
await browser.waitForElementByCss('#pages-retry-error')
expect(await browser.elementByCss('#pages-retry-error').text()).toBe(
'`unstable_retry()` can only be used in the App Router. Use `reset()` in the Pages Router.'
)
})
})
import { nextTestSetup } from 'e2e-utils'
describe('app-dir - unstable_catchError', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('should recover Client Component error after reset', async () => {
const browser = await next.browser('/client-component')
// Try triggering and resetting a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigger-button')
.click()
.waitForElementByCss('#error-boundary-message')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
'this is a test'
)
await browser
.elementByCss('#reset')
.click()
.waitForElementByCss('#error-trigger-button')
expect(await browser.elementByCss('#error-trigger-button').text()).toBe(
'Trigger Error!'
)
}
})
it('should recover Client Component error after unstable_retry', async () => {
const browser = await next.browser('/client-component')
// Try triggering and retrying a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigger-button')
.click()
.waitForElementByCss('#error-boundary-message')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
'this is a test'
)
await browser
.elementByCss('#retry')
.click()
.waitForElementByCss('#error-trigger-button')
expect(await browser.elementByCss('#error-trigger-button').text()).toBe(
'Trigger Error!'
)
}
})
it('should recover Server Component error after unstable_retry', async () => {
const browser = await next.browser('/server-component')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
isNextDev
? 'this is a test'
: 'An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.'
)
await browser.elementByCss('#retry').click().waitForElementByCss('#recover')
expect(await browser.elementByCss('#recover').text()).toBe('Recovered')
})
it('should recover after reset on Pages Router', async () => {
const browser = await next.browser('/pages-router')
await browser
.elementByCss('#pages-trigger')
.click()
.waitForElementByCss('#pages-error-message')
expect(await browser.elementByCss('#pages-error-message').text()).toBe(
'this is a pages test'
)
await browser.eval(`document.getElementById('pages-reset')?.click()`)
await browser.waitForElementByCss('#pages-trigger')
expect(await browser.elementByCss('#pages-trigger').text()).toBe(
'Trigger Error!'
)
})
it('should throw when unstable_retry is called on Pages Router', async () => {
const browser = await next.browser('/pages-router')
await browser
.elementByCss('#pages-trigger')
.click()
.waitForElementByCss('#pages-error-message')
await browser.eval(`document.getElementById('pages-retry')?.click()`)
await browser.waitForElementByCss('#pages-retry-error')
expect(await browser.elementByCss('#pages-retry-error').text()).toBe(
'`unstable_retry()` can only be used in the App Router. Use `reset()` in the Pages Router.'
)
})
})
import { useState } from 'react'
import { unstable_catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(
{ clearError }: { clearError: () => void },
{ error, reset, unstable_retry }: ErrorInfo
) {
const [retryError, setRetryError] = useState<string | null>(null)
return (
<>
<p id="pages-error-message">{error.message}</p>
<button
id="pages-reset"
onClick={() => {
clearError()
reset()
}}
>
Reset
</button>
<button
id="pages-retry"
onClick={() => {
try {
unstable_retry()
} catch (error) {
setRetryError((error as Error).message)
}
}}
>
Retry
</button>
{retryError ? <p id="pages-retry-error">{retryError}</p> : null}
</>
)
}
const ErrorBoundary = unstable_catchError(ErrorFallback)
function ErrorThrower({ shouldThrow }: { shouldThrow: boolean }) {
if (shouldThrow) {
throw new Error('this is a pages test')
}
return null
}
export default function Page() {
const [shouldThrow, setShouldThrow] = useState(false)
return (
<ErrorBoundary clearError={() => setShouldThrow(false)}>
<button id="pages-trigger" onClick={() => setShouldThrow(true)}>
Trigger Error!
</button>
<ErrorThrower shouldThrow={shouldThrow} />
</ErrorBoundary>
)
}
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