in javascript get the callstack that lead to error

爷,独闯天下 提交于 2019-12-07 04:11:56

问题


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.


回答1:


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/




回答2:


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:

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

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

  3. Write the callstack to a hidden div that you can tweak to be visible using the browser's developer tools.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!