Marc
Marc

Reputation: 9537

JQuery - get the actual line number within js file

I use the code below to handle ajax call erros. I would like to add the line number of that '$('body').append(...' line to be abble to echo it out. By line number, I mean the line number within my .js file. Wondering if that is possible to get the actual line number? Thank you in advance for your replies. Cheers. Marc

$.ajax({
    type: "POST",
    url: "myfile.php",
    error: function(jqXHR, textStatus, errorThrown) {

        $('body').append('aj.ERROR! [' + jqXHR.status + ' : ' + errorThrown + ']');
    },
    success: function(data) {
        // somecode
    }
});​

Upvotes: 0

Views: 2945

Answers (1)

Alnitak
Alnitak

Reputation: 339816

The only way I know to expose the current line number is with the window.onerror event handler, which has this signature:

window.onerror = function(msg, url, line) { ... }

so in theory you could trigger a real error in your code (throw ?) and then do your append in the error handler, e.g:

window.onerror = function(msg, url, line) {
    $('body').append(msg + ' at ' + url + ':' + line);
};

$.ajax({
    type: "POST",
    url: "myfile.php",
    error: function(jqXHR, textStatus, errorThrown) {
        throw 'aj.ERROR! [' + jqXHR.status + ' : ' + errorThrown + ']';
    },
    success: function(data) {
        // somecode
    }
});​

EDIT it works (in Chrome, at least...) - http://jsfiddle.net/alnitak/gLzY2/

Upvotes: 6

Related Questions