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.
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/
It depends a lot on what you want to do with the callstack--that is, what you mean by "log callstack or whatever."
For security reasons, it's obviously very unlikely that browsers will ever be allowing a page to give a javascript instruction to write an arbitrary file on the local machine's hard drive.
A few possibilities that you could employ:
Build the callstack in javascript, and send it as a detailed error message to an AJAX handler on the server where you can save errors in a logfile. (This assumes you have at least some cgi access on the server)
Write the callstack to the javascript console using console.log(), assuming the browser in question supports it. (Make sure to test for the existence of console and of console.log before writing.)
Write the callstack to a hidden div that you can tweak to be visible using the browser's developer tools.
Print the callstack in an alert(). (This is potentially useful as a developer, but it would be highly intrusive to an end user, so you will not want to leave the alert in the final deployed code.)
来源:https://stackoverflow.com/questions/9365065/in-javascript-get-the-callstack-that-lead-to-error