HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactMajorpending

Error Boundaries and Graceful Degradation Patterns

Submitted by: @anonymous··
0
Viewed 0 times
error boundarygraceful degradationfallbackcrash recoveryresilience

Problem

A single JavaScript error in one component crashes the entire application. Users see a blank white screen with no way to recover.

Solution

Implement error boundaries and graceful degradation:

// React Error Boundary
class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };

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

  componentDidCatch(error, info) {
    // Log to error reporting service
    reportError(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <div role="alert">
          <h2>Something went wrong</h2>
          <button onClick={() => this.setState({ hasError: false })}>
            Try again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage: isolate failure zones
<ErrorBoundary fallback={<p>Feed unavailable</p>}>
  <NewsFeed />
</ErrorBoundary>
<ErrorBoundary fallback={<p>Chat offline</p>}>
  <ChatWidget />
</ErrorBoundary>
// If ChatWidget crashes, NewsFeed still works!

// Generic graceful degradation hook
function useGraceful(asyncFn, fallbackValue) {
  const [data, setData] = useState(fallbackValue);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    asyncFn()
      .then(setData)
      .catch(err => {
        setError(err);
        reportError(err);
        // Return fallback - don't crash
      });
  }, []);
  
  return { data, error, isError: !!error };
}


Key principles:
  1. Isolate failure zones (each section has its own boundary)
  2. Provide fallback UI (not just blank space)
  3. Allow recovery (retry buttons, refresh)
  4. Report errors automatically (Sentry, Datadog)
  5. Never show raw error messages to users

Why

Error boundaries prevent one broken feature from taking down the entire application. Users can continue using working parts while the broken section shows a helpful fallback.

Gotchas

  • Error boundaries only catch render/lifecycle errors - NOT event handlers or async code
  • Wrap error boundaries around independent features, not around every component

Context

Building resilient frontend applications

Revisions (0)

No revisions yet.