Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch in JavaScript : how to get stack trace or line number of the original error

Tags:

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

like image 484
Greg Bala Avatar asked Jun 11 '12 22:06

Greg Bala


2 Answers

Try to use e.lineNumber. For example:

try {
   var i = v.WillGenerateError;
} catch (e) {
   alert(e.lineNumber);
}
like image 129
Victor Avatar answered Oct 21 '22 21:10

Victor


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).

like image 32
Pit Avatar answered Oct 21 '22 20:10

Pit