ComponentDidCatch not working inside react component

2.5k Views Asked by At

I have this component. Inside componentDidMount I created an object and try to throw the error. But the my componentDidCatch has not been called instead breaks my page!

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

  componentDidCatch(error, errorInfo) {
    // Catch errors in any child components and re-renders with an error message
    this.setState({
      error,
      errorInfo
    });
    console.log({ error, errorInfo });
  }

  componentDidMount() {
    const d = {}
    console.log(d.d.d)
  }

  render() {
    console.log("458454545454")
    if (this.state.error) {
      console.log("Error occurred")
    }
    return(<div>dffdfdfdfdfd</div>)
  }
}
2

There are 2 best solutions below

1
On

componentDidCatch

This lifecycle is invoked after an error has been thrown by a descendant component.

componentDidCatch doesn't catch errors thrown by the same component.

0
On

You should add static getDerivedStateFromError if you want to render some UI after catching an error.

Also, Error Boundaries not catch an errors thrown in the error boundary itself (that's why I add FaultyComponent throwing an actual error).

function FaultyComponent() {
  throw new Error("Test error");

  return <span>Faulty</span>;
}

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }
  
  static getDerivedStateFromError(error) {    
    return { hasError: true };  
  }
  
  componentDidCatch(error, errorInfo) {
    console.log('componentDidCatch', { error, errorInfo });
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    
    return this.props.children;
  }
}

function App() {
  return (
    <ErrorBoundary>
      <FaultyComponent />
    </ErrorBoundary>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>