Javascript Stack Trace in IE (or maybe just a simple Javascript error)

I came across this method to create a Javascript stack trace (to fix IE bug): http://pastie.org/253058.txt , which is really useful, but when I call it, the stack trace I get is for code the script itself ?!

Is it possible to modify this code to create a common stack trace? Or is there a better way to get the stack trace in IE?

(function () { YOUR_NAMESPACE.getStackTrace = (function () { var mode; try {(0)()} catch (e) { mode = e.stack ? 'Firefox' : window.opera ? 'Opera' : 'Other'; } switch (mode) { case 'Firefox' : return function () { try {(0)()} catch (e) { return e.stack.replace(/^.*?\n/,''). replace(/(?:\ n@ :0)?\s+$/m,''). replace(/^\(/gm,'{anonymous}('). split("\n"); } }; case 'Opera' : return function () { try {(0)()} catch (e) { var lines = e.message.split("\n"), ANON = '{anonymous}', lineRE = /Line\s+(\d+).*?in\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i, i,j,len; for (i=4,j=0,len=lines.length; i<len; i+=2) { if (lineRE.test(lines[i])) { lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + RegExp.$2 + ':' + RegExp.$1) + ' -- ' + lines[i+1].replace(/^\s+/,''); } } lines.splice(j,lines.length-j); return lines; } }; default : return function () { var curr = arguments.callee.caller, FUNC = 'function', ANON = "{anonymous}", fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [],j=0, fn,args,i; while (curr) { fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON; args = stack.slice.call(curr.arguments); i = args.length; while (i--) { switch (typeof args[i]) { case 'string' : args[i] = '"'+args[i].replace(/"/g,'\\"')+'"'; break; case 'function': args[i] = FUNC; break; } } stack[j++] = fn + '(' + args.join() + ')'; curr = curr.caller; } return stack; }; } })(); 
+6
javascript debugging
source share
2 answers

This getStackTrace() function creates a stack trace of the function with which you called getStackTrace() . It does not create a stack trace of the error you caught. For example, you should use it to try to figure out how a particular function is called:

 function foo() { // debug how this is being called alert(YOUR_NAMESPACE.getStackTrace()); } 

Or add additional error information that you raise:

 function foo() { // signal something went wrong var error = new Error("error in foo"); if (!error.stack) error.stack = YOUR_NAMESPACE.getStackTrace(); throw error; } 

You can not use it as follows:

 try { foo(); } catch (e) { alert(YOUR_NAMESPACE.getStackTrace(e)); } 

Here is a good description of what kind of stack information you can get - and from which browsers - when an error occurs: Three painful ways to get a stack trace in Javascript (link to Archive.org replaces a dead link)

+12
source share

You might be better off using the IE 8 built-in debugger.

-one
source share

All Articles