daisy-client / src /components /ErrorBoundary.tsx
Jessedbrown's picture
feat/init-daisy-client
6d643ca
Raw History Blame Contribute Delete
1.5 kB
import { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="flex min-h-[400px] flex-col items-center justify-center rounded-lg border border-red-200 bg-red-50 p-8">
<div className="text-center">
<h2 className="mb-2 text-lg font-semibold text-red-800">
Something went wrong
</h2>
<p className="mb-4 text-sm text-red-600">
{this.state.error?.message ?? 'An unexpected error occurred'}
</p>
<button
onClick={() =>
this.setState({ hasError: false, error: undefined })
}
className="rounded bg-red-600 px-4 py-2 text-white hover:bg-red-700"
>
Try again
</button>
</div>
</div>
);
}
return this.props.children;
}
}