2025-09-17 18:43:43 +09:00
|
|
|
"use client";
|
|
|
|
|
|
|
|
|
|
import { Component, ReactNode, ErrorInfo } from "react";
|
2025-09-20 11:35:40 +09:00
|
|
|
import { log } from "@customer-portal/logging";
|
2025-09-17 18:43:43 +09:00
|
|
|
|
|
|
|
|
interface ErrorBoundaryState {
|
|
|
|
|
hasError: boolean;
|
|
|
|
|
error?: Error;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface ErrorBoundaryProps {
|
|
|
|
|
children: ReactNode;
|
|
|
|
|
fallback?: ReactNode;
|
|
|
|
|
onError?: (error: Error, errorInfo: ErrorInfo) => void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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) {
|
2025-09-19 16:34:10 +09:00
|
|
|
// Log to external error service in production
|
|
|
|
|
if (process.env.NODE_ENV === 'production') {
|
|
|
|
|
// TODO: Send to error tracking service (Sentry, LogRocket, etc.)
|
|
|
|
|
} else {
|
2025-09-20 11:35:40 +09:00
|
|
|
log.error("ErrorBoundary caught an error", {
|
|
|
|
|
error: error.message,
|
|
|
|
|
stack: error.stack,
|
|
|
|
|
componentStack: errorInfo.componentStack
|
|
|
|
|
});
|
2025-09-19 16:34:10 +09:00
|
|
|
}
|
2025-09-17 18:43:43 +09:00
|
|
|
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-red-600">Something went wrong</h2>
|
|
|
|
|
<p className="text-gray-600">
|
|
|
|
|
{this.state.error?.message || "An unexpected error occurred"}
|
|
|
|
|
</p>
|
|
|
|
|
<button
|
|
|
|
|
onClick={() => this.setState({ hasError: false, error: undefined })}
|
|
|
|
|
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
|
|
|
|
|
>
|
|
|
|
|
Try again
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return this.props.children;
|
|
|
|
|
}
|
|
|
|
|
}
|