72 lines
2.2 KiB
TypeScript
Raw Normal View History

"use client";
import { Component, ReactNode, ErrorInfo } from "react";
import { logger } from "@/core/logger";
import { Button } from "@/components/atoms/button";
interface ErrorBoundaryState {
hasError: boolean;
error?: Error | undefined;
}
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode | undefined;
onError?: ((error: Error, errorInfo: ErrorInfo) => void) | undefined;
}
/**
* Error boundary component for catching and handling React errors
*/
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
override componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Log to external error service in production
if (process.env.NODE_ENV === "production") {
// Integration point: Send to error tracking service (Sentry, LogRocket, etc.)
// Example: Sentry.captureException(error, { contexts: { react: { componentStack: info.componentStack } } });
} else {
logger.error("ErrorBoundary caught an error", {
error: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack,
});
}
this.props.onError?.(error, errorInfo);
}
override render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="flex items-center justify-center h-64">
<div className="text-center space-y-4">
<h2 className="text-lg font-semibold text-danger">Something went wrong</h2>
<p className="text-muted-foreground">
{process.env.NODE_ENV === "development"
? this.state.error?.message || "An unexpected error occurred"
: "An unexpected error occurred. Please try again."}
</p>
<Button onClick={() => this.setState({ hasError: false, error: undefined })}>
Try again
</Button>
</div>
</div>
);
}
return this.props.children;
}
}