64 lines
1.8 KiB
TypeScript
64 lines
1.8 KiB
TypeScript
|
|
import React, { Component, type ReactNode } from 'react';
|
|||
|
|
|
|||
|
|
interface Props {
|
|||
|
|
children: ReactNode;
|
|||
|
|
fallback?: ReactNode;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
interface State {
|
|||
|
|
hasError: boolean;
|
|||
|
|
error?: Error;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Concise Error Boundary following DRY principles
|
|||
|
|
*/
|
|||
|
|
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: React.ErrorInfo) {
|
|||
|
|
// Simplified error reporting
|
|||
|
|
console.error('UI Error:', error, errorInfo);
|
|||
|
|
|
|||
|
|
// Optional: Report to backend
|
|||
|
|
fetch('/api/error-report', {
|
|||
|
|
method: 'POST',
|
|||
|
|
headers: { 'Content-Type': 'application/json' },
|
|||
|
|
body: JSON.stringify({
|
|||
|
|
error: error.message,
|
|||
|
|
stack: error.stack,
|
|||
|
|
timestamp: new Date().toISOString()
|
|||
|
|
})
|
|||
|
|
}).catch(() => {}); // Silent fail for error reporting
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
render() {
|
|||
|
|
if (this.state.hasError) {
|
|||
|
|
return this.props.fallback || (
|
|||
|
|
<div className="flex flex-col items-center justify-center min-h-[200px] p-6 bg-red-50 border border-red-200 rounded-lg">
|
|||
|
|
<div className="text-4xl text-red-500 mb-4">⚠️</div>
|
|||
|
|
<h2 className="text-lg font-semibold text-red-700 mb-2">Something went wrong</h2>
|
|||
|
|
<p className="text-sm text-red-600 mb-4 text-center">
|
|||
|
|
The chat component encountered an error. Please refresh the page and try again.
|
|||
|
|
</p>
|
|||
|
|
<button
|
|||
|
|
onClick={() => this.setState({ hasError: false, error: undefined })}
|
|||
|
|
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
|
|||
|
|
>
|
|||
|
|
🔄 Retry
|
|||
|
|
</button>
|
|||
|
|
</div>
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return this.props.children;
|
|||
|
|
}
|
|||
|
|
}
|