首页 > 解决方案 > Global Error Handling In React Application

问题描述

I am having a medium sized React App using React-redux and other libs. in most circumstances i am handling the error the using Try catch and dispatching to my service, but every now and then i get a user which tries to access the page from mobile web with a old chrome / firefox / etc . I am not able to get the error stack for these from my system but when i simulate it i can get hold of the error in the console .

errors like

enter image description here

I am trying to write a global error handler for the same but it never seems to work . Things i have tried writing a ErrorBoundary and placing it where my redux provider is placed, but for unsupported systems like older firefox and chrome it fails even before this .

Tried writing a onerror function in the index.html and even in the app.js file but still the error is never caught.

export const ErrorHandler = () => {
  window.addEventListener('unhandledrejection', function (e) {
    alert('RAHUL'+ e.reason.messagea);// i want to send the error to backend here
  });

  window.onerror = function (msg: string, url: string, lineNo: number, columnNo: number, error: Error) {
    const string = msg.toLowerCase();
    const substring = "script error";
    if (string.indexOf(substring) > -1) {
      alert('RAHUL'+'Script Error: See Browser Console for Detail');// i want to send the error to backend here
    } else {
      const message = [
        'Message: ' + msg,
        'URL: ' + url,
        'Line: ' + lineNo,
        'Column: ' + columnNo,
        'Error object: ' + JSON.stringify(error)
      ].join(' - ');

      alert('RAHUL'+ message); // i want to send the error to backend here
    }
    return false;
  };
};

I have looked at this question and others of the same type for reference.

Update

In our build system the React Assets are uploaded to a CDN while doing a build as we have a custom build solution and then inject to the jsp page which serves the assets , and as i was digging more into the error any external script error is not caught by window.onerror can be one of the solves , but for use cases like this how do we implement a global error handler

标签: javascriptreactjserror-handling

解决方案


推荐阅读