When using TRY-CATCH in JavaScript, how to get the line number of the line that caused the error?
On many browsers, the below code will work great and I will get the stack trace that points to the actual line that throw the exception.
However, some browsers do not have "e.stack". IPhone's safari is one example.
Is there someway to get the line number that will work for all browsers?
try
{
// lots of code here
var i = v.WillGenerateError; // how to get this line number in catch??
// lots of code here
}
catch (e)
{
alert (e.stack) // this will work on chrome, FF. will no not work on safari
alert (e.line) // this will work on safari but not on IPhone
}
Many thanks!
UPDATE: I found that e.line works on safari but still not available on IPhone, latest iOS version
Try to use e.lineNumber
.
For example:
try {
var i = v.WillGenerateError;
} catch (e) {
alert(e.lineNumber);
}
Full compatability with all browsers
var aux = err.stack.split("\n");
aux.splice(0, 2); //removing the line that we force to generate the error (var err = new Error();) from the message
aux = aux.join('\n"');
throw message + ' \n' + aux;
Error: myError at :4:11 at Object.InjectedScript._evaluateOn (:777:140). at Object.InjectedScript._evaluateAndWrap (:710:34). at Object.InjectedScript.evaluate (:626:21).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With