Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in javascript get the callstack that lead to error

The problem is not getting the callstack in general, which can be done as described here: http://eriwen.com/javascript/js-stack-trace/ but rather in accessing the callstack that triggered the event, from the handler of the event.

In particular I'm interested in logging the callstack from the window error event

window.onerror = function(msg, url, line) { 
 //callstack // would be nice to have.
//log callstack or whatever. (note this can be done w/ ajax and service, and is not the question at hand.
}

but I do know how to log the error. (I use jquery's .ajax, and a service)

Will browsers make this possible ever? Is it currently possible? Maybe I am going about this the wrong way. How can I add a simple function (i.e. not modify all the functions in my codebase) to detect whenever there is an error, and also log the call stack.

Thanks for the answers so far and sorry if the question was initially poorly worded.

like image 905
user420667 Avatar asked Feb 20 '12 16:02

user420667


People also ask

How do I get an error stack?

Use the console. trace() method to get the stack trace from an error. The console. trace() method outputs the stack trace and shows the call path taken to reach the point at which the method was called.

What is Callstack JavaScript?

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

How can I check my browser stack trace?

You can easily see the stack trace in JavaScript by adding the following into your code: console. trace(); And you'll get an outputted stack trace.


1 Answers

The Error object has a non-standard stack property on Mozilla, it seems to work in Google Chrome too, not IE9.

function test() {
  try {//can't think of anything that causes an exception?
      throw new Error("boo");
  }
  catch(e)
  {
      alert(e.stack);
  }
}
test();​

See the fiddle: http://jsfiddle.net/Cq5RJ/

like image 136
gideon Avatar answered Nov 03 '22 00:11

gideon