title: Logging javascript errors within Google Analytics
body: <p>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:</p>
  
  <pre><code>$(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) {
          }
      });
  });
  </code></pre>
  
  <p>This is successfully firing the events to Analytics for example:</p>
  
  <p><a href="https://i.stack.imgur.com/iNH7p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iNH7p.png" alt="Google Analytics"></a></p>
  
  <p>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.</p>
  
  <p>Any ideas why this isn't sending the error message along with the error?</p>
  
  <p>EDIT</p>
  
  <p>It turns out I was declaring the window.onerror function incorrectly.  The following works correctly:</p>
  
  <pre><code>window.onerror = function (message, source, lineno, colno, error) {
      try {
          sendAnalyticsEvent('js error', message, source + ':  ' + lineno);
      } catch(e) {
      }
  };
  </code></pre>