Capturing React Errors Globally

error-handling, exception, javascript, react-redux, reactjs

Solution

Doc refs: https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

Real case of implementation example:

// app.js
const MOUNT_NODE = document.getElementById('app');

const render = (messages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <ErrorBoundary>
            <App />
          </ErrorBoundary>
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE
  );
};

// ErrorBoundary component
export default class ErrorBoundary {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          // error message
        </div>
      );
    }

    return this.props.children;
  }
}

Problem

I'm new to React. I want to capture all react uncaught and unexpected errors/warnings and i would like to log the errors to an external api. I know its possible by Try Catch method but I'm planning to have it globally so that other developer need not to write the code each and every time. I tried `window.onerror/addEventListener('error', function(e){}` which only captures the Javascript errors but not react errors. This is similar to following post How do I handle exceptions?. But the solution given didn't meet my needs. Can someone help me on this?

Original source

Related problems