Error-logging for javascript on client side

前端 未结 7 1893
走了就别回头了
走了就别回头了 2020-12-08 01:02

My project which contains a lot of pages with forms. This is a backend of banking CRM system, so any error during working process is to be captured and investigated. On the

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 01:32

    If your website is using Google Analytics, you can do what I do:

    window.onerror = function(message, source, lineno, colno, error) {
      if (error) message = error.stack;
      ga('send', 'event', 'window.onerror', message, navigator.userAgent);
    }
    

    A few comments on the code above:

    • For modern browsers, the full stack trace is logged.
    • For older browsers that don't capture the stack trace, the error message is logged instead. (Mostly earlier iOS version in my experience).
    • The user's browser version is also logged, so you can see which OS/browser versions are throwing which errors. That simplifies bug prioritization and testing.
    • This code works if you use Google Analytics with "analytics.js", like this. If you are using "gtag.js" instead, like this, you need to tweak the last line of the function. See here for details.

    Once the code is in place, this is how you view your users' Javascript errors:

    1. In Google Analytics, click the Behavior section and then the Top Events report.
    2. You will get a list of Event Categories. Click window.onerror in the list.
    3. You will see a list of Javascript stack traces and error messages. Add a column to the report for your users' OS/browser versions by clicking the Secondary dimension button and entering Event Label in the textbox that appears.
    4. The report will look like the screenshot below.
    5. To translate the OS/browser strings to more human-readable descriptions, I copy-paste them into https://developers.whatismybrowser.com/useragents/parse/

提交回复
热议问题