| 'use client' |
|
|
| import React, { 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' |
|
|
| export type ErrorComponent = React.ComponentType<{ |
| error: Error |
| |
| |
| reset?: () => void |
| }> |
|
|
| export interface ErrorBoundaryProps { |
| children?: React.ReactNode |
| errorComponent: ErrorComponent | undefined |
| errorStyles?: React.ReactNode | undefined |
| errorScripts?: React.ReactNode | undefined |
| } |
|
|
| interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps { |
| pathname: string | null |
| errorComponent: ErrorComponent |
| } |
|
|
| interface ErrorBoundaryHandlerState { |
| error: Error | null |
| previousPathname: string | null |
| } |
|
|
| export class ErrorBoundaryHandler extends React.Component< |
| ErrorBoundaryHandlerProps, |
| ErrorBoundaryHandlerState |
| > { |
| constructor(props: ErrorBoundaryHandlerProps) { |
| super(props) |
| this.state = { error: null, previousPathname: this.props.pathname } |
| } |
|
|
| static getDerivedStateFromError(error: Error) { |
| if (isNextRouterError(error)) { |
| |
| |
| throw error |
| } |
|
|
| return { error } |
| } |
|
|
| static getDerivedStateFromProps( |
| props: ErrorBoundaryHandlerProps, |
| state: ErrorBoundaryHandlerState |
| ): ErrorBoundaryHandlerState | null { |
| const { error } = state |
|
|
| |
| |
| |
| |
| if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { |
| if (error && handleHardNavError(error)) { |
| |
| return { |
| error: null, |
| previousPathname: props.pathname, |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| 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 }) |
| } |
|
|
| |
| render(): React.ReactNode { |
| if (this.state.error) { |
| return ( |
| <> |
| <HandleISRError error={this.state.error} /> |
| {this.props.errorStyles} |
| {this.props.errorScripts} |
| <this.props.errorComponent |
| error={this.state.error} |
| reset={this.reset} |
| /> |
| </> |
| ) |
| } |
|
|
| return this.props.children |
| } |
| } |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| export function ErrorBoundary({ |
| errorComponent, |
| errorStyles, |
| errorScripts, |
| children, |
| }: ErrorBoundaryProps & { |
| children: React.ReactNode |
| }): JSX.Element { |
| |
| |
| |
| |
| const pathname = useUntrackedPathname() |
| if (errorComponent) { |
| return ( |
| <ErrorBoundaryHandler |
| pathname={pathname} |
| errorComponent={errorComponent} |
| errorStyles={errorStyles} |
| errorScripts={errorScripts} |
| > |
| {children} |
| </ErrorBoundaryHandler> |
| ) |
| } |
|
|
| return <>{children}</> |
| } |
|
|