“undefined” randomly appended in 1% of requested urls on my website since 12 june 2012

前端 未结 8 2195

Since 12 june 2012 11:20 TU, I see very weirds errors in my varnish/apache logs.

Sometimes, when an user has requested one page, several seconds later I see a simila

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 06:10

    This sounds like a race condition where a variable is not getting properly initialized before getting used. Considering this is not an AJAX issue according to your comments, there will be a couple of ways of figuring this out, listed below.

    Hookup a Javascript exception Logger: this will help you catch just about all random javascript exceptions in your log. Most of the time programmatic errors will bubble up here. Put it before any scripts. You will need to catch these on the server and print them to your logs for analysis later. This is your first line of defense. Here is an example:

    window.onerror = function(m,f,l) {
        var e = window.encodeURIComponent;
        new Image().src = "/jslog?msg=" + e(m) + "&filename=" + e(f) + "&line=" + e(l) + "&url=" + e(window.location.href);
    };
    

    Search for window.location: for each of these instances you should add logging or check for undefined concats/appenders to your window.location. For example:

    function myCode(loc) {
        // window.location.href = loc; // old 
        typeof loc === 'undefined' && window.onerror(...); //new
        window.location.href = loc; //new
    }
    

    or the slightly cleaner:

    window.setLocation = function(url) { 
       /undefined/.test(url) ? 
             window.onerror(...) : window.location.href = url;       
    }
    
    function myCode(loc) {
        //window.location.href = loc; //old
        window.setLocation(loc); //new
    } 
    

    If you are interested in getting stacktraces at this stage take a look at: https://github.com/eriwen/javascript-stacktrace

    Grab all unhandled undefined links: Besides window.location The only thing left are the DOM links themselves. The third step is to check all unhandeled DOM links for your invalid URL pattern (you can attach this right after jQuery finishes loading, earlier better):

    $("body").on("click", "a[href$='undefined']", function() {
        window.onerror('Bad link: ' + $(this).html()); //alert home base
    });
    

    Hope this is helpful. Happy debugging.

提交回复
热议问题