Capturing React Errors Globally

10,593

Solution 1

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;
  }
}

Solution 2

A thing to note is that errors in async methods like async componentDidMount won't be caught in a error boundary.

https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

Since not all errors will be caught we decided to use vanilla JavaScript window.onerror and window.onunhandledrejection in our project.

Complete question and answer:

https://stackoverflow.com/a/64319415/3850405

Share:
10,593
Jeev
Author by

Jeev

Updated on June 09, 2022

Comments

  • Jeev
    Jeev almost 2 years

    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?

  • softmarshmallow
    softmarshmallow about 3 years
    example with hooks?
  • Jorge Novo
    Jorge Novo about 2 years
    Sorry but ErrorBoundary does not catch all exceptions reactjs.org/docs/…