reactjs try catch in render does not catch children errors

Viewed 40386

I'm trying to add error catching to the render function of a component. This works fine when I throw an error in the actual render function, but if there are errors in the children of the component, the try does not catch the errors (or they are intercepted by the child component error handlers, I'm not sure?)

Is there anyway to force the errors to the parent.

const SimpleComponent = React.createClass({
    render: function(){
        try{
            throw 'new error'
            return <div>{this.props.children}</div>
        }catch(e){
            console.log('error', e);        
        }
    }
})

The above works

const SimpleComponent = React.createClass({
    render: function(){
        try{
            return <div>{this.props.children}</div>
        }catch(e){
            console.log('error', e);        
        }
    }
})

const ChildComponent = React.createClass({
    render: function(){
        throw 'child error'
    }
})

<SimpleComponent>
    <ChildComponent />
</SimpleComponent>

This above does not catch

3 Answers

Use componentDidCatch() method from react 16.

Check this for more info

Related