import { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null
};
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log to error reporting service
this.setState({
error: error,
errorInfo: errorInfo
});
// Send to monitoring service
if (typeof window !== 'undefined') {
// Example: Send to Sentry, LogRocket, etc.
console.error('Error Boundary caught:', {
error: error.toString(),
componentStack: errorInfo.componentStack
});
}
}
resetError = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback({
error: this.state.error,
errorInfo: this.state.errorInfo,
resetError: this.resetError
});
}
return (
<div className="error-boundary">
<h1>Oops! Something went wrong</h1>
<details style={{ whiteSpace: 'pre-wrap' }}>
<summary>Error Details</summary>
<p>{this.state.error && this.state.error.toString()}</p>
<p>{this.state.errorInfo && this.state.errorInfo.componentStack}</p>
</details>
<button onClick={this.resetError}>Try Again</button>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;