37 lines
1.0 KiB
TypeScript
37 lines
1.0 KiB
TypeScript
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
|||
|
|
|
||
|
|
interface ErrorBoundaryProps {
|
||
|
|
children: ReactNode;
|
||
|
|
fallback?: ReactNode;
|
||
|
|
}
|
||
|
|
|
||
|
|
interface ErrorBoundaryState {
|
||
|
|
hasError: boolean;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Catches render-time errors in the tree and shows a fallback UI. */
|
||
|
|
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||
|
|
state: ErrorBoundaryState = { hasError: false };
|
||
|
|
|
||
|
|
static getDerivedStateFromError(): ErrorBoundaryState {
|
||
|
|
return { hasError: true };
|
||
|
|
}
|
||
|
|
|
||
|
|
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||
|
|
console.error('Unhandled error in component tree', error, info.componentStack);
|
||
|
|
}
|
||
|
|
|
||
|
|
render(): ReactNode {
|
||
|
|
if (this.state.hasError) {
|
||
|
|
return (
|
||
|
|
this.props.fallback ?? (
|
||
|
|
<div className="flex min-h-screen items-center justify-center px-4 text-center">
|
||
|
|
<p className="text-sm text-gray-600">Something went wrong. Please reload the page.</p>
|
||
|
|
</div>
|
||
|
|
)
|
||
|
|
);
|
||
|
|
}
|
||
|
|
return this.props.children;
|
||
|
|
}
|
||
|
|
}
|