b6aa5fdce145c12636ac508e234fe0d8f52bb9d1
[lhc/web/wiklou.git] / resources / src / mediawiki.base / mediawiki.errorLogger.js
1 /**
2 * Try to catch errors in modules which don't do their own error handling.
3 *
4 * @class mw.errorLogger
5 * @singleton
6 */
7 ( function () {
8 'use strict';
9
10 mw.errorLogger = {
11 /**
12 * Fired via mw.track when an error is not handled by local code and is caught by the
13 * window.onerror handler.
14 *
15 * @event global_error
16 * @param {string} errorMessage Error errorMessage.
17 * @param {string} url URL where error was raised.
18 * @param {number} lineNumber Line number where error was raised.
19 * @param {number} [columnNumber] Line number where error was raised. Not all browsers
20 * support this.
21 * @param {Error|Mixed} [errorObject] The error object. Typically an instance of Error, but anything
22 * (even a primitive value) passed to a throw clause will end up here.
23 */
24
25 /**
26 * Install a window.onerror handler that will report via mw.track, while preserving
27 * any previous handler.
28 *
29 * @param {Object} window
30 */
31 installGlobalHandler: function ( window ) {
32 // We will preserve the return value of the previous handler. window.onerror works the
33 // opposite way than normal event handlers (returning true will prevent the default
34 // action, returning false will let the browser handle the error normally, by e.g.
35 // logging to the console), so our fallback old handler needs to return false.
36 var oldHandler = window.onerror || function () {
37 return false;
38 };
39
40 /**
41 * Dumb window.onerror handler which forwards the errors via mw.track.
42 *
43 * @param {string} errorMessage
44 * @param {string} url
45 * @param {number} lineNumber
46 * @param {number} [columnNumber]
47 * @param {Error|Mixed} [errorObject]
48 * @return {boolean} True to prevent the default action
49 * @fires global_error
50 */
51 window.onerror = function ( errorMessage, url, lineNumber, columnNumber, errorObject ) {
52 mw.track( 'global.error', { errorMessage: errorMessage, url: url,
53 lineNumber: lineNumber, columnNumber: columnNumber, errorObject: errorObject } );
54 return oldHandler.apply( this, arguments );
55 };
56 }
57 };
58
59 mw.errorLogger.installGlobalHandler( window );
60 }() );