Home > Back-end >  Errorboundary doesn't capture errors when simple component calls dictionary which errors
Errorboundary doesn't capture errors when simple component calls dictionary which errors

Time:07-08

I have the default error boundary mentioned in the react docs and I have a dictionary that would normally be filled with functions I can execute. I've specifically created a test case below which will error out because a particular function doesn't exist in the dictionary, I'm expecting the error boundary to catch this, however, it doesn't appear to work, what might be going on?

The simple component that should error out, but parts of it should still render:

export const App = () => {
    return 
          <ErrorBoundary>
            <Suspense fallback={<LoadingIcon/>}>
              <div>this should show #1</div>
              <ErrorBoundary>
               <SimpleComponent />
              </ErrorBoundary>
            </Suspense>
        </ErrorBoundary>
});


export const SimpleComponent: FC = ({}) => {
    const mydictionary: Dictionary<() => JSX.Element> = {};

    return (
        <div>
           stuff that should still render. #2
            <ErrorBoundary>
                <div>{mydictionary['nonexistentvalue']()}</div>
            </ErrorBoundary>
        </div>
    );
};

The error boundary:

export class ErrorBoundary extends React.Component<{}, { hasError: any }> {
    constructor(props: any) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error: any) {
        // Update state so the next render will show the fallback UI.
        console.log('err', error);
        return { hasError: true };
    }

    componentDidCatch(error: any, errorInfo: any) {
        this.setState({ hasError: true });
        console.error('Help', error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            // You can render any custom fallback UI
            return <h1>Something went wrong here.</h1>;
        }

        return this.props.children;
    }
}

What I get is just the single Something went wrong here. on the page.

CodePudding user response:

Try to wrap your SimpleComponent with your ErrorBoundary component. When SimpleComponent will be wrapped error boundary component should work correctly. Docs says that error boundary component can handle only issues of children components wrapped with this error boundary component. On the same level it won't work.

<ErrorBoundary>
  <SimpleComponent/>
</ErrorBoundary>

CodePudding user response:

I will assume you are already wrapping your component with the ErrorBoundary.

Try setting your hasError state in the componentDidCatch method and let me know if that helps.

componentDidCatch(error, errorInfo) {
  this.setState({ hasError: true});
}
  • Related