| 1 |
/** |
| 2 |
* Error Boundary Component |
| 3 |
* |
| 4 |
* Catches and handles React errors gracefully |
| 5 |
* |
| 6 |
* @package ThinkRank |
| 7 |
* @since 1.0.0 |
| 8 |
*/ |
| 9 |
|
| 10 |
import { Component } from '@wordpress/element'; |
| 11 |
import { __ } from '@wordpress/i18n'; |
| 12 |
import { Notice, Button } from '@wordpress/components'; |
| 13 |
|
| 14 |
/** |
| 15 |
* Error Boundary Component |
| 16 |
*/ |
| 17 |
class ErrorBoundary extends Component { |
| 18 |
constructor(props) { |
| 19 |
super(props); |
| 20 |
this.state = { hasError: false, error: null, errorInfo: null }; |
| 21 |
} |
| 22 |
|
| 23 |
static getDerivedStateFromError(error) { |
| 24 |
// Update state so the next render will show the fallback UI |
| 25 |
return { hasError: true }; |
| 26 |
} |
| 27 |
|
| 28 |
componentDidCatch(error, errorInfo) { |
| 29 |
// Log error details |
| 30 |
this.setState({ |
| 31 |
error: error, |
| 32 |
errorInfo: errorInfo |
| 33 |
}); |
| 34 |
|
| 35 |
// Log to console for debugging |
| 36 |
console.error('ThinkRank Error Boundary caught an error:', error, errorInfo); |
| 37 |
} |
| 38 |
|
| 39 |
handleReload = () => { |
| 40 |
// Reload the page to recover from error |
| 41 |
window.location.reload(); |
| 42 |
}; |
| 43 |
|
| 44 |
render() { |
| 45 |
if (this.state.hasError) { |
| 46 |
return ( |
| 47 |
<div className="thinkrank-error-boundary"> |
| 48 |
<Notice status="error" isDismissible={false}> |
| 49 |
<h3>{__('Something went wrong', 'thinkrank')}</h3> |
| 50 |
<p> |
| 51 |
{__('ThinkRank encountered an unexpected error. Please try reloading the page.', 'thinkrank')} |
| 52 |
</p> |
| 53 |
|
| 54 |
<div className="error-actions"> |
| 55 |
<Button isPrimary onClick={this.handleReload}> |
| 56 |
{__('Reload Page', 'thinkrank')} |
| 57 |
</Button> |
| 58 |
</div> |
| 59 |
|
| 60 |
{process.env.NODE_ENV === 'development' && ( |
| 61 |
<details className="error-details"> |
| 62 |
<summary>{__('Error Details (Development)', 'thinkrank')}</summary> |
| 63 |
<pre> |
| 64 |
{this.state.error && this.state.error.toString()} |
| 65 |
<br /> |
| 66 |
{this.state.errorInfo.componentStack} |
| 67 |
</pre> |
| 68 |
</details> |
| 69 |
)} |
| 70 |
</Notice> |
| 71 |
</div> |
| 72 |
); |
| 73 |
} |
| 74 |
|
| 75 |
return this.props.children; |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
export default ErrorBoundary; |
| 80 |
|