Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs try catch in render does not catch children errors

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

like image 886
l2silver Avatar asked Mar 11 '16 04:03

l2silver


1 Answers

Use componentDidCatch() method from react 16.

Check this for more info

like image 112
John Avatar answered Oct 09 '22 20:10

John