1

I'm working on the error handling for a jQuery practise project and I was wondering if it is possible to get the line were the error occured. For example:

function number(x) {
    if (x === 1) {
        alert("ok");
    } else {
        alert("Invalid number was given on line ...")
    }
}

number(2);​

Now I would like to alert instead of the ... the line the error occured in. Thanks in advance.

Raidri
  • 17,258
  • 9
  • 62
  • 65
minute acc
  • 11
  • 2

2 Answers2

0

you can use window.onerror in your script,like this

window.onerror = function(msg, url, line) {
       alert("Error:"+msg+'at'+url+':'+line);
};
Buzz
  • 6,030
  • 4
  • 33
  • 47
  • My understanding is that this only works with a real error and not with a error you create yourself with a if else function, right? – minute acc Nov 05 '12 at 12:30
0

Example 1:

This example shows how to catch an exception and displays information about the error:

try {
    unknownFunction ();
}
catch(e) {
document.write ("The error message: <b>" + e.message + "</b>");
if ('number' in e) {
    document.write ("<br />");
    document.write ("The error code: <b>" + e.number + "</b>");
}
if ('lineNumber' in e) {
    document.write ("<br />");
    document.write ("The error occurred at line: <b>" + e.lineNumber + "</b>");
}
}

Example 2:

This example shows how to create and catch a custom exception:

try {
    var err = new Error ();
    err.message = "My first error message";
     if (err.fileName === undefined) { // IE, Opera, Google Chrome and Safari
    err.fileName = document.location.href;
    }
    throw err;
}
catch(e) {
document.write ("The error message: <b>" + e.message + "</b><br />");
document.write ("The error occurred in the following file: <b>" + e.fileName + "</b>");
topcat3
  • 2,561
  • 6
  • 33
  • 57