tahamajs/IE / Projects /front /src /components /common /ErrorBoundary.tsx
tahamajs's picture
download
raw
8.56 kB
// src/components/common/ErrorBoundary.tsx
import { Component, ReactNode, useState } from "react";
import { AlertCircle, RefreshCw, Home, Bug, Copy, ChevronDown, ChevronUp } from "lucide-react";
import { toast } from "react-toastify";
interface Props {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
resetKeys?: any[];
showDetails?: boolean;
}
interface State {
hasError: boolean;
error: Error | null;
errorInfo: React.ErrorInfo | null;
showStack: boolean;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
showStack: false
};
}
static getDerivedStateFromError(error: Error): Partial<State> {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error("Uncaught error:", error, errorInfo);
this.setState({ errorInfo });
// Call custom error handler if provided
if (this.props.onError) {
this.props.onError(error, errorInfo);
}
// Log to error tracking service (Sentry, LogRocket, etc.)
this.logErrorToService(error, errorInfo);
}
componentDidUpdate(prevProps: Props) {
// Reset error state when resetKeys change
if (this.state.hasError && this.props.resetKeys) {
const hasResetKeyChanged = this.props.resetKeys.some(
(key, index) => key !== prevProps.resetKeys?.[index]
);
if (hasResetKeyChanged) {
this.resetError();
}
}
}
logErrorToService = (error: Error, errorInfo: React.ErrorInfo) => {
// Keep the boundary self-contained unless a real error-tracking service is wired in.
if (process.env.NODE_ENV === "production") {
console.error("Captured error:", {
message: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack,
url: window.location.href,
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
});
}
};
resetError = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
showStack: false
});
};
handleReload = () => {
// Dispatch custom event for soft reload
window.dispatchEvent(new CustomEvent("app:soft-reload"));
// Avoid hard reloads while offline; they can trap the app in a reset loop.
if (typeof navigator !== "undefined" && !navigator.onLine) {
toast.info("You are offline. The app will keep the current screen until the network returns.");
return;
}
// Fallback to hard reload if needed and the browser is online.
setTimeout(() => {
if (this.state.hasError) {
window.location.reload();
}
}, 1000);
};
handleGoHome = () => {
window.location.href = "/";
};
handleCopyError = () => {
const errorText = `Error: ${this.state.error?.message}\n\nStack: ${this.state.error?.stack}\n\nComponent Stack: ${this.state.errorInfo?.componentStack}`;
navigator.clipboard.writeText(errorText);
// Show toast notification if available
if (typeof toast !== "undefined") {
toast.success("Error copied to clipboard");
}
};
toggleStack = () => {
this.setState(prev => ({ showStack: !prev.showStack }));
};
render() {
if (this.state.hasError) {
// Use custom fallback if provided
if (this.props.fallback) {
return this.props.fallback;
}
const isDev = process.env.NODE_ENV === "development";
const { error, errorInfo, showStack } = this.state;
return (
<div className="flex min-h-screen flex-col items-center justify-center bg-gradient-to-b from-red-50 to-white dark:from-gray-900 dark:to-gray-950 p-4">
<div className="w-full max-w-md rounded-2xl bg-white dark:bg-gray-800 shadow-xl overflow-hidden">
{/* Header */}
<div className="bg-red-600 p-6 text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-white/20 mb-4">
<AlertCircle className="w-8 h-8 text-white" />
</div>
<h1 className="text-2xl font-bold text-white">Something went wrong</h1>
<p className="text-white/80 text-sm mt-1">We encountered an unexpected error</p>
</div>
{/* Error Details */}
<div className="p-6">
<div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
<p className="text-red-700 dark:text-red-400 text-sm font-mono break-all">
{error?.message || "Unknown error occurred"}
</p>
</div>
{/* Stack Trace (Development only) */}
{isDev && errorInfo && (
<div className="mb-4">
<button
onClick={this.toggleStack}
className="flex items-center justify-between w-full p-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition"
>
<span className="flex items-center gap-2">
<Bug className="w-4 h-4" />
Technical Details
</span>
{showStack ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button>
{showStack && (
<div className="mt-2 p-3 bg-gray-100 dark:bg-gray-900 rounded-lg overflow-auto max-h-60">
<p className="text-xs font-mono text-gray-700 dark:text-gray-300 whitespace-pre-wrap">
{error?.stack}
{"\n\n"}
<strong>Component Stack:</strong>
{"\n"}
{errorInfo.componentStack}
</p>
</div>
)}
</div>
)}
{/* Action Buttons */}
<div className="flex flex-col gap-3">
<button
onClick={this.handleReload}
className="flex items-center justify-center gap-2 w-full py-2.5 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition"
>
<RefreshCw className="w-4 h-4" />
Try Again
</button>
<button
onClick={this.handleGoHome}
className="flex items-center justify-center gap-2 w-full py-2.5 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition"
>
<Home className="w-4 h-4" />
Go to Homepage
</button>
{isDev && (
<button
onClick={this.handleCopyError}
className="flex items-center justify-center gap-2 w-full py-2.5 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition text-sm"
>
<Copy className="w-4 h-4" />
Copy Error Details
</button>
)}
</div>
{/* Support Message */}
<p className="text-center text-xs text-gray-500 dark:text-gray-400 mt-4">
If the problem persists, please contact our support team.
<br />
<a href="/contact" className="text-primary hover:underline">Contact Support →</a>
</p>
</div>
</div>
</div>
);
}
return this.props.children;
}
}
// Optional: HOC to wrap components with ErrorBoundary
export function withErrorBoundary<P extends object>(
Component: React.ComponentType<P>,
fallback?: ReactNode
) {
return function WithErrorBoundary(props: P) {
return (
<ErrorBoundary fallback={fallback}>
<Component {...props} />
</ErrorBoundary>
);
};
}
// Optional: Hook to manually trigger error boundary reset
export function useErrorBoundary() {
const [error, setError] = useState<Error | null>(null);
const resetError = () => setError(null);
if (error) {
throw error;
}
return { throwError: setError, resetError };
}

Xet Storage Details

Size:
8.56 kB
·
Xet hash:
4952b96ead96ff40e1ca2d11a6542369233573f7fced7f11def50ccfcff83652

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.