Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing React Errors Globally

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?

like image 917
Jeev Avatar asked Oct 25 '16 08:10

Jeev


People also ask

How do you handle errors globally in React?

Error handling with Error Boundaries — For class components. Error boundaries are the most straightforward and effective way to handle errors that occur within your React components. You can create an error boundary component by including the life cycle method componentDidCatch(error, info) if you use class component.

How do you handle global exception in react JS?

An uncaught Javascript error can crash the entire app. The Error Boundary is a concept introduced to prevent app crashes by catching Javascript errors at the higher application level. Error Boundaries are React class components that wrap up all child components and catch their errors.

How do you catch error messages in React?

Error boundaries were introduced in React 16 as a way to catch and handle JavaScript errors that occur in the UI parts of our component. So error boundaries only catch errors that occur in a lifecycle method, render method, and inside Hooks like useEffect .

What is global error handling?

Global Error HandlerThis class implements the ErrorHandler class and contains a handleError method. This method is called whenever an error is thrown somewhere in the application. The error is passed as a parameter and can be processed further inside the method.


2 Answers

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;
  }
}
like image 95
Mosè Raguzzini Avatar answered Sep 22 '22 20:09

Mosè Raguzzini


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

like image 27
Ogglas Avatar answered Sep 22 '22 20:09

Ogglas