codigo0/src/components/ErrorBoundary.tsx

105 lines
2.8 KiB
TypeScript
Raw Normal View History

import React, { Component, ErrorInfo, ReactNode } from 'react';
import { AlertTriangle, Home, RefreshCw } from 'lucide-react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): State {
return {
hasError: true,
error,
errorInfo: null,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, errorInfo);
this.setState({
error,
errorInfo,
});
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="max-w-md w-full space-y-6">
<div className="text-center">
<AlertTriangle className="w-16 h-16 text-destructive mx-auto mb-4" />
<h1 className="text-2xl font-bold text-foreground mb-2">
Algo salió mal
</h1>
<p className="text-muted-foreground mb-6">
La aplicación encontró un error inesperado. Por favor, intenta recargar la página.
</p>
</div>
{process.env.NODE_ENV === 'development' && this.state.error && (
<div className="p-4 bg-muted border border-border rounded-lg">
<p className="text-sm font-mono text-destructive mb-2">
{this.state.error.toString()}
</p>
{this.state.errorInfo && (
<pre className="text-xs text-muted-foreground overflow-auto max-h-40">
{this.state.errorInfo.componentStack}
</pre>
)}
</div>
)}
<div className="flex flex-col gap-3">
<Button onClick={this.handleReset} className="w-full">
<RefreshCw className="w-4 h-4 mr-2" />
Intentar de nuevo
</Button>
<Link to="/">
<Button variant="outline" className="w-full">
<Home className="w-4 h-4 mr-2" />
Ir al inicio
</Button>
</Link>
</div>
</div>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;