Skip to content

Instantly share code, notes, and snippets.

@petewarden
Last active December 11, 2015 14:49
Show Gist options
  • Save petewarden/4617127 to your computer and use it in GitHub Desktop.
Save petewarden/4617127 to your computer and use it in GitHub Desktop.
// Call like wrapNamespaceInTracing(jetpac, 'jetpac');
g_callStack = [];
window.onerror = function(inputMessage, url, line) {
if (typeof g_callStack !== 'undefined') {
inputMessage += ' - stack=[' + g_callStack.join(' -> ') + ']';
g_callStack = [];
}
var message = '**** Javascript error **** ' + inputMessage + ' at ' + url + ':' + line;
console.log(message);
var _p = 'none';
if (typeof KM !== 'undefined') {
_p = KM.i();
}
var errorUrl = '/jserror?';
errorUrl += 'message=' + encodeURIComponent(inputMessage) + '&';
errorUrl += 'script=' + encodeURIComponent(url) + '&';
errorUrl += 'line=' + encodeURIComponent(line) + '&';
errorUrl += '_p=' + encodeURIComponent(_p) + '&';
errorImage = new Image(1, 1); // A deliberate global
errorImage.src = errorUrl;
};
function logBefore(name, fn, options) {
var fullName = options.moduleName + ':' + name + '()';
// console.log("calling " + fullName);
g_callStack.push(fullName);
}
function logAfter(name, fn, options) {
var fullName = options.moduleName + ':' + name;
// console.log("called " + fullName);
g_callStack.pop();
}
function wrapNamespaceInTracing(object, name) {
wrapFunctions({
context: object,
before: logBefore,
after: logAfter,
moduleName: name
});
}
function wrapFunctions(options) {
var context = options.context;
var before = options.before;
var after = options.after;
var name, fn;
for (name in context) {
fn = context[name];
if (typeof fn === 'function') {
context[name] = (function(name, fn, options) {
var args = arguments;
var wrappingFunction = function() {
if (before) {
before.apply(this, args);
}
var result = fn.apply(this, arguments);
if (after) {
after.apply(this, args);
}
return result;
};
wrappingFunction.prototype = fn.prototype;
for (var i in fn) {
wrappingFunction[i] = fn[i];
}
return wrappingFunction;
})(name, fn, options);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment