React js Error Boundary doesn't work with Promise Catch

Viewed 5066

We have a Error Boundary component :

import React from 'react';
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorMessage:''};
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true, errorMessage: error });
    // You can also log the error to an error reporting service
  }

  render() {
    if (this.state.hasError) {
      debugger
      // You can render any custom fallback UI  
      return <h1>{this.state.errorMessage.toString()}</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

And We are using it like this :

ReactDOM.render(
    <Provider store={store}>
        <Router>
            <CookiesProvider>
                <ErrorBoundary>
                    <NetworkMgmt />
                </ErrorBoundary>
            </CookiesProvider>
        </Router>
    </Provider>,
     document.getElementById('root')
);

After that i tries to throw the error by using below code snippet, but that doesn't call Error Boundary componentDidCatch(), instead it throws the unhandled exception.

    dataService.getNetworkSummary().then(function (result) {
        debugger
        self.networks = result;
        self.setState({
            items: result.slice(0, 20),
            total: result.length,
            skip: 0,
            pageSize: 20,
            pageable: {
                buttonCount: 5,
                info: true,
                type: 'numeric',
                pageSizes: [20, 40, 60, 80, 100],
                previousNext: true
            },
            sortable:{
                allowUnsort: true,
                mode: 'single',
                sortDir:'Asc'
            }

        })
    }).catch(err =>
         {
             throw new Error("This is my error");
         });

Is there any way we can do it in correct manner.

1 Answers

As in the promise you are catching the error, so that means that it will not show error in the component because you already have handled the error in the function. The purpose of catch is the handle the error in that block do not disturb the component. If you want to throw error manually you can use

throw 'Some Error';

or you can remove the catch block, which I would not recommend.

UPDATE: Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

Related