Handle React Errors in v15 🙌 (handle_unstableError Example)

Edit: for ReactV16 you need to read about componentDidCatch

If you’re writing reactjs daily you have probably seen this error:

Example: http://jsfiddle.net/uqkkLaxs/ (view the source)

So whats the deal?! React doesn’t know how to handle your errors! When `render()` returns an `Error` instead of a `<Component/>`, it cannot mount that shit and instead spits out the above note. (it only knows how to render components!)

TL:DR; React v15 has a solution.

unstable_handleError: function(){
this.setState({error: "oops"})

`unstable_handleError()` is a new function for all components which is called when render or children render an error. Here’s an example component:

class Boundary extends React.Component {
      unstable_handleError() {
this.setState({error: true});
      render() {
if (this.state.error){
return <SafeComponent/>
} else {
return <ComponentWithErrors/>

On mount there is no error, so it renders `<ComponentWithErrors/>`.

Assuming the `<ComponentWithErrors/>` throws an error, this component’s `unstable_handleError()` will be called and state will update to `error: true`.

When state updates, the `<SafeComponent/>` is instead rendered!

How do I know this is coming?!?! the TESTS in the source code!


Good luck and happy reacting.