I just wanted to expand a bit on @Simon_Weaver 's excellent answer to provide error reports with a few additional details:
- Make sure
ga()
is defined before trying to call it (as an Error could be triggered before the Analytics library is loaded).
- Log Exception line numbers and column index in the Analytics Reports (although minified JavaScript code used in production might be difficult to read).
- Execute any previously-defined
window.onerror
callback.
/**
* Send JavaScript error information to Google Analytics.
*
* @param {Window} window A reference to the "window".
* @return {void}
* @author Philippe Sawicki <https://github.com/philsawicki>
*/
(function (window) {
// Retain a reference to the previous global error handler, in case it has been set:
var originalWindowErrorCallback = window.onerror;
/**
* Log any script error to Google Analytics.
*
* Third-party scripts without CORS will only provide "Script Error." as an error message.
*
* @param {String} errorMessage Error message.
* @param {String} url URL where error was raised.
* @param {Number} lineNumber Line number where error was raised.
* @param {Number|undefined} columnNumber Column number for the line where the error occurred.
* @param {Object|undefined} errorObject Error Object.
* @return {Boolean} When the function returns true, this prevents the
* firing of the default event handler.
*/
window.onerror = function customErrorHandler (errorMessage, url, lineNumber, columnNumber, errorObject) {
// Send error details to Google Analytics, if the library is already available:
if (typeof ga === 'function') {
// In case the "errorObject" is available, use its data, else fallback
// on the default "errorMessage" provided:
var exceptionDescription = errorMessage;
if (typeof errorObject !== 'undefined' && typeof errorObject.message !== 'undefined') {
exceptionDescription = errorObject.message;
}
// Format the message to log to Analytics (might also use "errorObject.stack" if defined):
exceptionDescription += ' @ ' + url + ':' + lineNumber + ':' + columnNumber;
ga('send', 'exception', {
'exDescription': exceptionDescription,
'exFatal': false, // Some Error types might be considered as fatal.
'appName': 'Application_Name',
'appVersion': '1.0'
});
}
// If the previous "window.onerror" callback can be called, pass it the data:
if (typeof originalWindowErrorCallback === 'function') {
return originalWindowErrorCallback(errorMessage, url, lineNumber, columnNumber, errorObject);
}
// Otherwise, Let the default handler run:
return false;
};
})(window);
// Generate an error, for demonstration purposes:
//throw new Error('Crash!');
Edit: As @Simon_Weaver duly noted, Google Analytics now has documentation about Exception Tracking (which I should have linked to in my original answer -- sorry, rookie mistake!):