React

Wat zijn Error Boundaries en hoe catch je errors?

Error boundaries voorkomen hele app crashes.

Home/Categorieën/React/Wat zijn Error Boundaries en hoe catch je errors?

Error Boundary basics

Class component met componentDidCatch lifecycle. Catches errors in child components. Toont fallback UI.

Wat error boundaries NOT catchen

Event handlers (use try/catch) Async code Server-side rendering Fouten in Error Boundary zelf

Code Voorbeelden

JAVASCRIPTError Boundary class
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    console.log('Error:', error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong</h1>;
    }
    return this.props.children;
  }
}

Relevante trefwoorden

errorboundaryerror handling