in javascript get the callstack that lead to error

落花浮王杯 提交于 2019-12-05 08:49:26

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:

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

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