Logging javascript errors within Google Analytics

2019-07-17 19:48发布

问题:

I'm trying to get information on JavaScript errors that are occurring within my web application and logging these using events within Google Analytics. I'm doing this as follows:

$(document).ready(function() {
    var sendAnalyticsEvent = function(category, action, label) {
        if (window.ga) {
            window.ga('send', 'event', category, action, label);
        }
    };

    window.onerror = function(error) {
        try {
            sendAnalyticsEvent('JavaScript Error', error.message, error.filename + ':  ' + error.lineno);
        } catch(e) {
        }
    };

    $(document).ajaxError(function(e, request, settings) {
        try {
            sendAnalyticsEvent('Ajax Error', settings.url, e.result);
        } catch(e) {
        }
    });
});

This is successfully firing the events to Analytics for example:

However when I click into 'JavaScript Error' it doesn't give me any other information, for example the error message that should have been sent with the code above.

Any ideas why this isn't sending the error message along with the error?

EDIT

It turns out I was declaring the window.onerror function incorrectly. The following works correctly:

window.onerror = function (message, source, lineno, colno, error) {
    try {
        sendAnalyticsEvent('js error', message, source + ':  ' + lineno);
    } catch(e) {
    }
};

回答1:

You're sending the error message as the Event Label dimensions, but that report is looking at the Event Category dimension. If you click on Event Label, you should see it.

That being said, why not use exception tracking instead of event tracking to measure this? Exception tracking was built exactly for this use case.



回答2:

In you case the problem is with declaring window.onerror() inside $(document).ready(), it will only catch errors after jQuery initialisation. You need to declare it as early as possible.

Add following into <head>:

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','_watchdog');

_watchdog('create', 'UA-xxxxxxx-x', 'auto');

window.onerror = function(msg) {
  _watchdog('send', 'exception', { 'exDescription': msg });

  _watchdog('send', 'event', {
    eventCategory: 'javascript',
    eventAction: 'error',
    eventLabel: msg,
    transport: 'beacon'
  });
}
</script>

After that you will start receiving events with 'error' type under 'Javascript' category.

Unfortunately, in Event Tracking, your error messages will be limited by 500 Bytes, so you will not be able to understand a problem properly, however you will know that something is going wrong :)

For mo detailed errors use Exception Tracking