"use client" import { Component, type ErrorInfo, type ReactNode } from "react" import { Button } from "@/components/ui/button" import { AlertTriangle } from "lucide-react" interface Props { children: ReactNode fallback?: ReactNode } interface State { hasError: boolean error: Error | null } export class ErrorBoundary extends Component { constructor(props: Props) { super(props) this.state = { hasError: false, error: null } } static getDerivedStateFromError(error: Error): State { return { hasError: true, error } } componentDidCatch(error: Error, errorInfo: ErrorInfo) { // 记录错误到日志服务 this.logError(error, errorInfo) } logError = async (error: Error, errorInfo: ErrorInfo) => { try { await fetch("/api/log-error", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ message: error.message, stack: error.stack, componentStack: errorInfo.componentStack, url: window.location.href, timestamp: new Date().toISOString(), }), }) } catch (e) { console.error("Failed to log error:", e) } } handleRetry = () => { this.setState({ hasError: false, error: null }) } render() { if (this.state.hasError) { if (this.props.fallback) { return this.props.fallback } return (

出现了一些问题

应用遇到了错误。我们已记录此问题并将尽快修复。

{process.env.NODE_ENV === "development" && (

{this.state.error?.stack}

)}
) } return this.props.children } }