62 lines
1.8 KiB
TypeScript
62 lines
1.8 KiB
TypeScript
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
|
import { AlertTriangle, RefreshCw } from 'lucide-react';
|
|
|
|
interface Props {
|
|
children: ReactNode;
|
|
fallbackTitle?: string;
|
|
}
|
|
|
|
interface State {
|
|
hasError: boolean;
|
|
error: Error | null;
|
|
}
|
|
|
|
export class ErrorBoundary extends Component<Props, State> {
|
|
public state: State = {
|
|
hasError: false,
|
|
error: null,
|
|
};
|
|
|
|
public static getDerivedStateFromError(error: Error): State {
|
|
return { hasError: true, error };
|
|
}
|
|
|
|
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
|
console.error('ErrorBoundary caught an error:', error, errorInfo);
|
|
}
|
|
|
|
public handleReset = () => {
|
|
this.setState({ hasError: false, error: null });
|
|
};
|
|
|
|
public render() {
|
|
if (this.state.hasError) {
|
|
return (
|
|
<div className="p-8 bg-white border border-rose-200 rounded-3xl shadow-sm text-center space-y-4 max-w-lg mx-auto my-8">
|
|
<div className="h-12 w-12 rounded-2xl bg-rose-50 text-rose-600 flex items-center justify-center mx-auto">
|
|
<AlertTriangle className="h-6 w-6" />
|
|
</div>
|
|
<div>
|
|
<h3 className="text-base font-black text-slate-900">
|
|
{this.props.fallbackTitle || 'Something went wrong in this section'}
|
|
</h3>
|
|
<p className="text-xs text-slate-500 font-medium mt-1">
|
|
{this.state.error?.message || 'An unexpected rendering error occurred.'}
|
|
</p>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
onClick={this.handleReset}
|
|
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 shadow"
|
|
>
|
|
<RefreshCw className="h-3.5 w-3.5" />
|
|
Try Again
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return this.props.children;
|
|
}
|
|
}
|