我遇到了这个方法来生成一个
Javascript堆栈跟踪(修复IE特定的bug):
http://pastie.org/253058.txt这听起来真的很有用,但是当我调用它时,我得到的堆栈跟踪是针对脚本本身的代码的吗?!
可以更改此代码以生成一般堆栈跟踪吗?或者有更好的方法在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 = [],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; }; } })();
解决方法
此getStackTrace()函数创建函数的堆栈跟踪,您可以从中调用getStackTrace().它不会创建您捕获的错误的堆栈跟踪.例如,您将使用它来试图弄清楚如何调用特定函数:
function foo() { // debug how this is being called alert(YOUR_NAMESPACE.getStackTrace()); }
function foo() { // signal something went wrong var error = new Error("error in foo"); if (!error.stack) error.stack = YOUR_NAMESPACE.getStackTrace(); throw error; }
你不能这样使用它:
try { foo(); } catch (e) { alert(YOUR_NAMESPACE.getStackTrace(e)); }
以下是您可以获得的堆栈信息以及发生错误时从哪些浏览器获取的详细信息:Three Painful Ways to Obtain a Stack Trace in Javascript(Archive.org链接替换死链接)