import { Component, ErrorInfo, ReactNode } from 'react'
interface Props {
children: ReactNode
}
interface State {
hasError: boolean
error?: Error
}
export default class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
}
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 render() {
if (this.state.hasError) {
return (
<div className="p-8 text-center">
<h2 className="text-2xl font-bold text-red-500 mb-4">Something went wrong</h2>
<p className="text-gray-400 mb-4">{this.state.error?.message}</p>
<button
onClick={() => this.setState({ hasError: false, error: undefined })}
className="px-4 py-2 bg-blue-600 rounded hover:bg-blue-700"
>
Try again
</button>
</div>
)
}
return this.props.children
}
}
export { ErrorBoundary }