Error Boundaries - Overview

Description

Limitations

Error Boundaries - Creation

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

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Error Boundaries - componentDidCatch

componentDidCatch(error, info) {

  /* Example stack information:
     in ComponentThatThrows (created by App)
     in ErrorBoundary (created by App)
     in div (created by App)
     in App
  */
  logComponentStackToMyService(info.componentStack);
}

CodePen

Error Boundaries - Within Event Handlers

function MyComponent (props) {

  const [error, setError] = useState(null)

  const handleClick = () => {
    try {
      // Do something that could fail
    } catch (error) {
      setError(error);
    }
  }

  if (error) {
    return <h1>Caught an error.</h1>
  }
  return <div onClick={this.handleClick}>Click Me</div>
}

Error Boundaries - Live Example

See the Pen oMRpQg by Joshua Burke (@Dangeranger) on CodePen.

Error Boundaries - Stack Traces

Default

With Create-React-App

 Previous Next 

Outline

[menu]

/