Kodax

Error Boundaries — مقدمة React

Error Boundaries

Error Boundaries هي مكونات React تلتقط أخطاء JavaScript في شجرة المكونات الفرعية.

إنشاء Error Boundary

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    // إرسال الخطأ لخدمة تتبع الأخطاء
    console.error('Error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>حدث خطأ ما!</h2>
          <p>نعتذر عن هذا الخطأ، يرجى تحديث الصفحة.</p>
          <button onClick={() => window.location.reload()}>
            تحديث الصفحة
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// الاستخدام
function App() {
  return (
    <ErrorBoundary>
      <Header />
      <ErrorBoundary>
        <MainContent />
      </ErrorBoundary>
      <Footer />
    </ErrorBoundary>
  );
}

ملاحظات مهمة

- Error Boundaries لا تلتقط أخطاء:

- Event handlers (استخدم try-catch)

- Async code (استخدم .catch())

- Server-side rendering

- أخطاء في Error Boundary نفسه

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error('Caught error:', error);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || <h2>حدث خطأ!</h2>;
    }
    return this.props.children;
  }
}

// استخدام مع fallback مخصص
function App() {
  return (
    <ErrorBoundary fallback={<CustomErrorUI />}>
      <Dashboard />
    </ErrorBoundary>
  );
}
اختبر فهمك