11

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?

Community
  • 1
  • 1
Jeev
  • 131
  • 1
  • 1
  • 9

3 Answers3

3

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;
  }
}
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
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

Ogglas
  • 62,132
  • 37
  • 328
  • 418
-1

This will help: https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

Basically, with React 16 and above you can use componentDidCatch() lifecycle method in your parent most component to log all the uncaught exceptions.

Shriharsha KL
  • 317
  • 1
  • 2
  • 11