😍 😘s

ReactV16 Error Handler (componentDidCatch example)

A look at componentDidCatch and componentStack

Blair Anderson
Jul 27, 2017 · 2 min read

React has long needed a solution for handling errors.

For ReactV15 use handle_unstableError

Since early React development, it was fairly common for a small component throwing an error to break your entire application.

As confirmed recently on github, React Core has decided to implement a built-in function called componentDidCatch ! I personally requested some input on this October 21st 2015, but the main ticket started tracking this error/solution back from Nov 3, 2014!

We have patiently been waiting 996 Days!

Lets take a look at it!

React 16 will provide a built-in function called componentDidCatch which is triggered if the render() function throws an error. Below you can click the “button will throw” which updates state to throw an error.

Important note:

Errors are caught in render but are not caught in event handlers. The example button “button will not throw” will not utilize Error Boundry and will still be shown in the javascript console.

I highly recommend clicking through into this codesandbox to view the example components. Below is a basic PotentialError Component

class PotentialError extends React.Component {   
  constructor(props) {     
    super(props);     
    this.state = { error: false };
  }
  componentDidCatch(error, info) {     
    this.setState({ error, info });
  }
  render() {
    if (this.state.error) {
      return <h1>Error: {this.state.error.toString()}</h1>;
    }
    return this.props.children;   
  } 
}

Then at the top or anywhere you can use it like so:

<PotentialError><AwesomeApp /></PotentialError>

Another awesome feature of componentDidCatch is the info object which contains the error Stack!

{this.state.info && this.state.info.componentStack}

This will tell you exactly where your component flopped!

Let me know how you’re playing with error boundaries!

Blair Anderson

Written by

Amazon Manufacturer’s Representative @ https://www.AndersonAssociates.net/