Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally logging jQuery Errors (Event & DOM errors)

Since systems these days are becoming more and more Javascript (jQuery, AJAX, etc) oriented, we've been trying to get more and more Error logging happening for any of these things.


My concern is that within jQuery itself, when normal DOM manipulation / jQuery events are created or executed, window.onerror is unable to catch these, and this might help make debugging bugs in production faster, by having them logged on a server

In this article from 2008 (.onerror & jQuery bind try/catch{}), they add a try/catch {} to the jQuery.bind() event and even the document.ready event. Now that everything goes through the .on() event this article is a bit dated, but I feel like logic could still work...

Has anyone tried implementing such a jQuery overwrite (try/catch system) into their own Projects?

Basically I want to continue using jQuery from the CDN, and just within one of our JS files - extend/override the .on() / $(document).ready() / etc events with these changes.

jQuery.fn.extend({ // <-- can this be extended / overwritten ?
    on: function(etc etc) {
        // same code just add the additional
        try {
            // try to execute the original .on()
        }
        catch (ex) {
            // log any errors / info (where/why/etc)
        }
    }
});

// or even some sort of try/catch for $(document).ready()?

The other typical error logging formats: (of course logging browser/OS/QueryString/etc too)

window.onerror = function (msg, url, line) {
    // Log General Javascript Errors
    // this won't log jQuery internal errors
};

$.ajaxSetup({ // Log AJAX Errors
    error: function (jqXHR, ajaxSettings, thrownError) { }
});
like image 321
Mark Pieszak - Trilon.io Avatar asked Nov 06 '12 20:11

Mark Pieszak - Trilon.io


1 Answers

We report JavaScript errors to the server in window.onerror and jQuery ajax errors, without overriding jQuery and it works well. If you want to override a jQuery function, you can do:

$.fn.oldOn = $.fn.on;
$.fn.on = function(a,b,c,d,e,f) {
    try {
        $(this).oldOn(a,b,c,d,e,f);
    }
    catch (ex) { ... }
};
like image 176
Craig Celeste Avatar answered Oct 07 '22 23:10

Craig Celeste