← Back to React Course | Chapter 13: Advanced React & Architecture | Lesson 1 of 14

Error Boundaries का उपयोग

एक error boundary आपके घर में एक circuit breaker जैसा है — अगर एक appliance short-circuit हो जाए, यह सिर्फ उस circuit को trip करता है पूरे घर को darkness में डालने के बजाय।
Syntax
markup
class ErrorBoundary extends React.Component {
  state = { hasError: false };

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

  componentDidCatch(error, info) {
    // log the error
  }

  render() {
    return this.state.hasError ? <p>Fallback UI</p> : this.props.children;
  }
}

<ErrorBoundary><Component /></ErrorBoundary>

Error Boundaries क्या Catch करते हैं

बिना एक error boundary के, rendering के दौरान कहीं भी thrown एक JavaScript error पूरे React component tree को unmount कर देता है, एक blank page दिखाते हुए। एक error boundary अपने child components द्वारा rendering, lifecycle methods, और constructors के दौरान thrown errors catch करता है, आपको एक blank screen के बजाय एक fallback UI दिखाने देते हुए।

Note: Risky या complex sections को अपने UI का अपनी own error boundary में wrap करें (जैसे untrusted third-party data render करने वाला एक widget)।
Warning: Error boundaries event handlers के अंदर के errors catch NOT करते (जैसे एक onClick handler throw करता है) — उन्हें regular try/catch चाहिए instead।

उदाहरण: What Error Boundaries Catch

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() { return { hasError: true }; }
  render() {
    if (this.state.hasError) return <p>Something went wrong.</p>;
    return this.props.children;
  }
}
function BuggyComponent() { throw new Error("Oops"); }
function App() {
  return <ErrorBoundary><BuggyComponent /></ErrorBoundary>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

componentDidCatch से Errors Log करना

getDerivedStateFromError (जो fallback UI दिखाने के लिए state update करता है) के साथ, componentDidCatch एक second lifecycle method है जो actual error और additional info receive करता है, commonly error को एक monitoring service पर log करने के लिए उपयोग किया जाता है बिना जो render हो रहा है उसे affect किए।

Note:
  • getDerivedStateFromError को purely state update करने पर focused रखें
  • Logging जैसे side effects के लिए componentDidCatch उपयोग करें।
Warning: componentDidCatch अकेले (getDerivedStateFromError के बिना) UI को एक fallback में update नहीं करेगा — typical pattern के लिए आपको दोनों methods एक साथ काम करने चाहिए।

उदाहरण: Logging Errors with componentDidCatch

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() { return { hasError: true }; }
  componentDidCatch(error, info) {
    console.log("Logged error:", error.message);
  }
  render() {
    if (this.state.hasError) return <p>Error logged and handled.</p>;
    return this.props.children;
  }
}
function BuggyComponent() { throw new Error("Simulated crash"); }
function App() {
  return <ErrorBoundary><BuggyComponent /></ErrorBoundary>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Multiple, Scoped Error Boundaries उपयोग करना

पूरे app के आस-पास एक giant error boundary के बजाय (जो किसी single error पर सब कुछ blank कर देगा), छोटे, independent sections को उनकी own boundaries में wrap करना impact limit करता है — अगर एक sidebar widget crash हो जाए, page का बाकी हिस्सा normally काम करता रहता है।

Note: अच्छी boundaries natural feature boundaries हैं: एक comments section, एक chart widget, एक third-party embed — हर एक independently recoverable।
Warning: एक single app-wide error boundary का मतलब है कहीं भी कोई भी error पूरे UI को blank कर देता है, boundaries उपयोग करने के ज़्यादातर benefit को defeat करते हुए।

उदाहरण: Using Multiple, Scoped Error Boundaries

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() { return { hasError: true }; }
  render() { return this.state.hasError ? <p>Widget failed to load.</p> : this.props.children; }
}
function BrokenWidget() { throw new Error("Widget crash"); }
function App() {
  return (
    <div>
      <p>This part still works fine.</p>
      <ErrorBoundary><BrokenWidget /></ErrorBoundary>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक error boundary को एक function component के रूप में लिखने की कोशिश करना — React 18 तक, error boundaries class components होनी चाहिए।
  2. यह उम्मीद करना कि एक error boundary event handlers में errors catch करेगी — यह सिर्फ rendering, lifecycle methods, और constructors के दौरान errors catch करती है।
  3. पूरे app को सिर्फ एक error boundary में wrap करना, इसलिए कहीं भी कोई error पूरे UI को ले जाता है सिर्फ broken section के बजाय।
चैप्टर सारांश
  • एक error boundary एक class component है जो अपने child component tree में rendering के दौरान JavaScript errors catch करता है।
  • getDerivedStateFromError और componentDidCatch दो lifecycle methods हैं जो यह behavior implement करते हैं।
  • Error boundaries event handlers, async code, या boundary की अपनी rendering में errors catch NOT करते।
  • UI के छोटे, independent sections को अलग boundaries में wrap करना किसी एक error का blast radius limit करता है।
ब्राउज़र सपोर्ट

React 16.0 से available (error boundaries introduced); React 18 तक अब भी एक class component चाहिए।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.