616

如果我自己抛出一个 JavaScript 异常(例如,throw "AArrggg"),我如何获得堆栈跟踪(在 Firebug 中或其他中)?现在我刚刚收到消息。

编辑:正如下面许多人发布的那样,可以获得JavaScript 异常的堆栈跟踪,但我想获得我的异常的堆栈跟踪。例如:

function foo() {
    bar(2);
}
function bar(n) {
    if (n < 2)
        throw "Oh no! 'n' is too small!"
    bar(n-1);
}

foo被调用时,我想获得一个堆栈跟踪,其中包括对foo, bar,的调用bar

4

25 回答 25

909

编辑 2(2017 年):

在所有现代浏览器中,您可以简单地调用:console.trace(); (MDN 参考)

编辑 1 (2013):

正如对原始问题的评论中指出的那样,一个更好(和更简单)的解决方案是使用对象的stack属性,Error如下所示:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

这将生成如下输出:

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6

给出调用函数的名称以及 URL、它的调用函数等。

原件(2009 年):

此代码段的修改版本可能会有所帮助:

function stacktrace() { 
  function st2(f) {
    return !f ? [] : 
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  }
  return st2(arguments.callee.caller);
}
于 2009-03-11T18:50:56.327 回答
213

请注意,chromium/chrome(其他使用 V8 的浏览器)和 Firefox 确实有一个方便的接口,可以通过Error对象的堆栈属性获取堆栈跟踪。

try {
   // Code throwing an exception
} catch(e) {
  console.log(e.stack);
}

它适用于基本异常以及您自己抛出的异常。(考虑到您使用 Error 类,这无论如何都是一个好习惯)。

查看V8 文档的详细信息

于 2010-11-16T23:47:33.327 回答
86

在 Firefox 中,您似乎不需要抛出异常。做就够了

e = new Error();
console.log(e.stack);
于 2013-02-27T20:38:35.150 回答
25

如果您有 firebug,则脚本选项卡中的所有错误选项都会中断。脚本到达断点后,您可以查看 firebug 的堆栈窗口:

截屏

于 2009-02-26T22:58:54.513 回答
17

正如对原始问题的评论中指出的那样,一个好的(且简单的)解决方案是使用对象的stack属性,Error如下所示:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

这将生成如下输出:

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6

给出调用函数的名称以及 URL 和行号、它的调用函数等。

我有一个非常精细和漂亮的解决方案,我为我目前正在从事的项目设计了它,并且我已经提取并重新设计了它以进行概括。这里是:

(function(context){
    // Only global namespace.
    var Console = {
        //Settings
        settings: {
            debug: {
                alwaysShowURL: false,
                enabled: true,
                showInfo: true
            },
            stackTrace: {
                enabled: true,
                collapsed: true,
                ignoreDebugFuncs: true,
                spacing: false
            }
        }
    };

    // String formatting prototype function.
    if (!String.prototype.format) {
        String.prototype.format = function () {
            var s = this.toString(),
                args = typeof arguments[0],
                args = (("string" == args || "number" == args) ? arguments : arguments[0]);
            if (!arguments.length)
                return s;
            for (arg in args)
                s = s.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
            return s;
        }
    }

    // String repeating prototype function.
    if (!String.prototype.times) {
        String.prototype.times = function () {
            var s = this.toString(),
                tempStr = "",
                times = arguments[0];
            if (!arguments.length)
                return s;
            for (var i = 0; i < times; i++)
                tempStr += s;
            return tempStr;
        }
    }

    // Commonly used functions
    Console.debug = function () {
        if (Console.settings.debug.enabled) {
            var args = ((typeof arguments !== 'undefined') ? Array.prototype.slice.call(arguments, 0) : []),
                sUA = navigator.userAgent,
                currentBrowser = {
                    firefox: /firefox/gi.test(sUA),
                    webkit: /webkit/gi.test(sUA),
                },
                aLines = Console.stackTrace().split("\n"),
                aCurrentLine,
                iCurrIndex = ((currentBrowser.webkit) ? 3 : 2),
                sCssBlack = "color:black;",
                sCssFormat = "color:{0}; font-weight:bold;",
                sLines = "";

            if (currentBrowser.firefox)
                aCurrentLine = aLines[iCurrIndex].replace(/(.*):/, "$1@").split("@");
            else if (currentBrowser.webkit)
                aCurrentLine = aLines[iCurrIndex].replace("at ", "").replace(")", "").replace(/( \()/gi, "@").replace(/(.*):(\d*):(\d*)/, "$1@$2@$3").split("@");

            // Show info if the setting is true and there's no extra trace (would be kind of pointless).
            if (Console.settings.debug.showInfo && !Console.settings.stackTrace.enabled) {
                var sFunc = aCurrentLine[0].trim(),
                    sURL = aCurrentLine[1].trim(),
                    sURL = ((!Console.settings.debug.alwaysShowURL && context.location.href == sURL) ? "this page" : sURL),
                    sLine = aCurrentLine[2].trim(),
                    sCol;

                if (currentBrowser.webkit)
                    sCol = aCurrentLine[3].trim();

                console.info("%cOn line %c{0}%c{1}%c{2}%c of %c{3}%c inside the %c{4}%c function:".format(sLine, ((currentBrowser.webkit) ? ", column " : ""), ((currentBrowser.webkit) ? sCol : ""), sURL, sFunc),
                             sCssBlack, sCssFormat.format("red"),
                             sCssBlack, sCssFormat.format("purple"),
                             sCssBlack, sCssFormat.format("green"),
                             sCssBlack, sCssFormat.format("blue"),
                             sCssBlack);
            }

            // If the setting permits, get rid of the two obvious debug functions (Console.debug and Console.stackTrace).
            if (Console.settings.stackTrace.ignoreDebugFuncs) {
                // In WebKit (Chrome at least), there's an extra line at the top that says "Error" so adjust for this.
                if (currentBrowser.webkit)
                    aLines.shift();
                aLines.shift();
                aLines.shift();
            }

            sLines = aLines.join(((Console.settings.stackTrace.spacing) ? "\n\n" : "\n")).trim();

            trace = typeof trace !== 'undefined' ? trace : true;
            if (typeof console !== "undefined") {
                for (var arg in args)
                    console.debug(args[arg]);

                if (Console.settings.stackTrace.enabled) {
                    var sCss = "color:red; font-weight: bold;",
                        sTitle = "%c Stack Trace" + " ".times(70);

                    if (Console.settings.stackTrace.collapsed)
                        console.groupCollapsed(sTitle, sCss);
                    else
                        console.group(sTitle, sCss);

                    console.debug("%c" + sLines, "color: #666666; font-style: italic;");

                    console.groupEnd();
                }
            }
        }
    }
    Console.stackTrace = function () {
        var err = new Error();
        return err.stack;
    }

    context.Console = Console;
})(window);

在GitHub 上查看(当前为 v1.2)!您可以像使用它一样使用它Console.debug("Whatever");,它会根据 中的设置Console打印输出和堆栈跟踪(或者只是简单的信息/根本没有额外的东西)。这是一个例子:

控制台.js

确保玩弄Console对象中的设置!您可以在轨迹线之间添加间距并将其完全关闭。这是Console.trace设置为false

没有痕迹

您甚至可以关闭显示的第一位信息(设置Console.settings.debug.showInfofalse)或完全禁用调试(设置Console.settings.debug.enabledfalse),这样您就不必再次注释掉调试语句了!把它们留在里面,这将无济于事。

于 2013-08-13T17:35:20.257 回答
11

我不认为有任何内置的东西可以使用,但是我确实找到了很多人自己滚动的例子。

于 2009-02-26T18:39:47.943 回答
9

即使你扔了它,你也可以访问实例的stackstacktrace在 Opera 中)属性。Error问题是,您需要确保使用throw new Error(string)(不要忘记的而不是throw string.

例子:

try {
    0++;
} catch (e) {
    var myStackTrace = e.stack || e.stacktrace || "";
}
于 2009-08-21T05:43:49.303 回答
9

使用 Chrome 浏览器,您可以使用console.trace方法:https ://developer.chrome.com/devtools/docs/console-api#consoletraceobject

于 2014-07-03T18:07:36.473 回答
7

这将为现代 Chrome、Opera、Firefox 和 IE10+ 提供堆栈跟踪(作为字符串数组)

function getStackTrace () {

  var stack;

  try {
    throw new Error('');
  }
  catch (error) {
    stack = error.stack || '';
  }

  stack = stack.split('\n').map(function (line) { return line.trim(); });
  return stack.splice(stack[0] == 'Error' ? 2 : 1);
}

用法:

console.log(getStackTrace().join('\n'));

它从堆栈中排除了它自己的调用以及 Chrome 和 Firefox(但不是 IE)使用的标题“错误”。

它不应该在旧浏览器上崩溃,而只是返回空数组。如果您需要更通用的解决方案,请查看stacktrace.js。它支持的浏览器列表确实令人印象深刻,但在我看来,它对于它的小任务来说非常大:37Kb 的缩小文本,包括所有依赖项。

于 2015-01-23T20:28:38.350 回答
7

尤金回答的更新:必须抛出错误对象才能让 IE(特定版本?)填充stack属性。以下应该比他当前的示例更好,并且应该避免undefined在 IE 中返回。

function stackTrace() {
  try {
    var err = new Error();
    throw err;
  } catch (err) {
    return err.stack;
  }
}

注意 1:这种事情应该只在调试时进行,并且在上线时禁用,尤其是在频繁调用的情况下。注意 2:这可能不适用于所有浏览器,但似乎适用于 FF 和 IE 11,非常适合我的需求。

于 2015-03-12T21:07:46.780 回答
6

在 Firebug 上获取真正的堆栈跟踪的一种方法是创建一个真正的错误,例如调用未定义的函数:

function foo(b){
  if (typeof b !== 'string'){
    // undefined Error type to get the call stack
    throw new ChuckNorrisError("Chuck Norris catches you.");
  }
}

function bar(a){
  foo(a);
}

foo(123);

或者使用console.error()后跟throw语句 sinceconsole.error()显示堆栈跟踪。

于 2012-03-14T03:43:20.823 回答
5

这个 polyfill 代码在现代(2017)浏览器(IE11、Opera、Chrome、FireFox、Yandex)中工作:

printStackTrace: function () {
    var err = new Error();
    var stack = err.stack || /*old opera*/ err.stacktrace || ( /*IE11*/ console.trace ? console.trace() : "no stack info");
    return stack;
}

其他答案:

function stackTrace() {
  var err = new Error();
  return err.stack;
}

不能在 IE 11 中工作!

使用arguments.callee.caller - 在任何浏览器中都不能在严格模式下工作!

于 2017-08-12T22:08:12.717 回答
3

在 Google Chrome(版本 19.0 及更高版本)中,只需抛出异常即可完美运行。例如:

/* file: code.js, line numbers shown */

188: function fa() {
189:    console.log('executing fa...');
190:    fb();
191: }
192:
193: function fb() {
194:    console.log('executing fb...');
195:    fc()
196: }
197:
198: function fc() {
199:    console.log('executing fc...');
200:    throw 'error in fc...'
201: }
202:
203: fa();

将在浏览器的控制台输出中显示堆栈跟踪:

executing fa...                         code.js:189
executing fb...                         code.js:194
executing fc...                         cdoe.js:199
/* this is your stack trace */
Uncaught error in fc...                 code.js:200
    fc                                  code.js:200
    fb                                  code.js:195
    fa                                  code.js:190
    (anonymous function)                code.js:203

希望这有帮助。

于 2012-06-08T11:18:24.747 回答
3

功能:

function print_call_stack(err) {
    var stack = err.stack;
    console.error(stack);
}

用例:

     try{
         aaa.bbb;//error throw here
     }
     catch (err){
         print_call_stack(err); 
     }
于 2016-03-23T07:09:10.697 回答
2
<script type="text/javascript"
src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script>
<script type="text/javascript">
    try {
        // error producing code
    } catch(e) {
        var trace = printStackTrace({e: e});
        alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n'));
        // do something else with error
    }
</script>

此脚本将显示错误

于 2015-10-30T10:46:50.973 回答
2
function stacktrace(){
  return (new Error()).stack.split('\n').reverse().slice(0,-2).reverse().join('\n');
}
于 2017-03-17T16:48:38.813 回答
2

至少在 Edge 2021 中:

console.groupCollapsed('jjjjjjjjjjjjjjjjj')
    console.trace()
    try {
        throw "kuku"
    } catch(e) {
        console.log(e.stack)
    }
console.groupEnd()
traceUntillMe()

你完了,我的朋友

于 2021-01-26T21:35:42.710 回答
1

有点晚了,但是,这是另一个解决方案,它自动检测arguments.callee 是否可用,如果没有,则使用 new Error().stack。在 chrome、safari 和 firefox 中测试。

2 个变体 - stackFN(n) 为您提供远离直接调用者的函数 n 的名称,而 stackArray() 为您提供一个数组,stackArray()[0] 是直接调用者。

在http://jsfiddle.net/qcP9y/6/尝试一下

// returns the name of the function at caller-N
// stackFN()  = the immediate caller to stackFN
// stackFN(0) = the immediate caller to stackFN
// stackFN(1) = the caller to stackFN's caller
// stackFN(2) = and so on
// eg console.log(stackFN(),JSON.stringify(arguments),"called by",stackFN(1),"returns",retval);
function stackFN(n) {
    var r = n ? n : 0, f = arguments.callee,avail=typeof f === "function",
        s2,s = avail ? false : new Error().stack;
    if (s) {
        var tl=function(x) { s = s.substr(s.indexOf(x) + x.length);},
        tr = function (x) {s = s.substr(0, s.indexOf(x) - x.length);};
        while (r-- >= 0) {
            tl(")");
        }
        tl(" at ");
        tr("(");
        return s;
    } else {
        if (!avail) return null;
        s = "f = arguments.callee"
        while (r>=0) {
            s+=".caller";
            r--;   
        }
        eval(s);
        return f.toString().split("(")[0].trim().split(" ")[1];
    }
}
// same as stackFN() but returns an array so you can work iterate or whatever.
function stackArray() {
    var res=[],f = arguments.callee,avail=typeof f === "function",
        s2,s = avail ? false : new Error().stack;
    if (s) {
        var tl=function(x) { s = s.substr(s.indexOf(x) + x.length);},
        tr = function (x) {s = s.substr(0, s.indexOf(x) - x.length);};
        while (s.indexOf(")")>=0) {
            tl(")");
            s2= ""+s;
            tl(" at ");
            tr("(");
            res.push(s);
            s=""+s2;
        }
    } else {
        if (!avail) return null;
        s = "f = arguments.callee.caller"
        eval(s);
        while (f) {
            res.push(f.toString().split("(")[0].trim().split(" ")[1]);
            s+=".caller";
            eval(s);
        }
    }
    return res;
}


function apple_makes_stuff() {
    var retval = "iPhones";
    var stk = stackArray();

    console.log("function ",stk[0]+"() was called by",stk[1]+"()");
    console.log(stk);
    console.log(stackFN(),JSON.stringify(arguments),"called by",stackFN(1),"returns",retval);
    return retval;
}



function apple_makes (){
    return apple_makes_stuff("really nice stuff");
}

function apple () {
    return apple_makes();
}

   apple();
于 2014-07-13T13:38:36.400 回答
1

你可以使用这个库http://www.stacktracejs.com/。这很好

从文档

您还可以传入自己的错误以获取 IE 或 Safari 5 中不可用的堆栈跟踪

<script type="text/javascript" src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script>
<script type="text/javascript">
    try {
        // error producing code
    } catch(e) {
        var trace = printStackTrace({e: e});
        alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n'));
        // do something else with error
    }
</script>
于 2014-10-21T21:07:48.063 回答
1

这是一个可以为您提供最大性能(IE 6+)和最大兼容性的答案。兼容IE 6!

    function stacktrace( log_result ) {
    	var trace_result;
    // IE 6 through 9 compatibility
    // this is NOT an all-around solution because
    // the callee property of arguments is depredicated
    /*@cc_on
    	// theese fancy conditinals make this code only run in IE
    	trace_result = (function st2(fTmp) {
    		// credit to Eugene for this part of the code
    		return !fTmp ? [] :
    			st2(fTmp.caller).concat([fTmp.toString().split('(')[0].substring(9) + '(' + fTmp.arguments.join(',') + ')']);
    	})(arguments.callee.caller);
    	if (log_result) // the ancient way to log to the console
    		Debug.write( trace_result );
    	return trace_result;
    @*/
    	console = console || Console;	// just in case
    	if (!(console && console.trace) || !log_result){
    		// for better performance in IE 10
    		var STerror=new Error();
    		var unformated=(STerror.stack || STerror.stacktrace);
    		trace_result = "\u25BC console.trace" + unformated.substring(unformated.indexOf('\n',unformated.indexOf('\n'))); 
    	} else {
    		// IE 11+ and everyone else compatibility
    		trace_result = console.trace();
    	}
    	if (log_result)
    		console.log( trace_result );
    	
    	return trace_result;
    }
// test code
(function testfunc(){
	document.write( "<pre>" + stacktrace( false ) + "</pre>" );
})();

于 2017-04-05T00:52:38.043 回答
0

在 Firefox 上比在 IE 上更容易获得堆栈跟踪,但基本上这是您想要做的:

将“有问题的”代码段包装在 try/catch 块中:

try {
    // some code that doesn't work
    var t = null;
    var n = t.not_a_value;
}
    catch(e) {
}

如果您要检查“错误”对象的内容,它包含以下字段:

e.fileName :问题来自的源文件/页面 e.lineNumber :出现问题的文件/页面中的行号 e.message :描述发生什么类型的错误的简单消息 e.name :类型发生的错误,在上面的示例中应该是 'TypeError' e.stack :包含导致异常的堆栈跟踪

我希望这能够帮到你。

于 2009-03-04T02:53:56.967 回答
0

我不得不用 IE11 研究 smartgwt 中的无限递归,所以为了更深入地研究,我需要一个堆栈跟踪。问题是,我无法使用开发控制台,因为那样复制更加困难。
在 javascript 方法中使用以下内容:

try{ null.toString(); } catch(e) { alert(e.stack); }
于 2014-10-15T12:28:59.543 回答
0

哇 - 我在 6 年内没有看到一个人建议我们stack在使用之前先检查是否可用!您在错误处理程序中可以做的最糟糕的事情是因为调用不存在的东西而引发错误。

正如其他人所说,虽然stack现在大多数情况下可以安全使用,但 IE9 或更早版本不支持它。

我记录了我的意外错误,堆栈跟踪非常重要。为了获得最大的支持,我首先检查是否Error.prototype.stack存在并且是一个函数。如果是这样,那么使用它是安全的error.stack

        window.onerror = function (message: string, filename?: string, line?: number, 
                                   col?: number, error?: Error)
        {
            // always wrap error handling in a try catch
            try 
            {
                // get the stack trace, and if not supported make our own the best we can
                var msg = (typeof Error.prototype.stack == 'function') ? error.stack : 
                          "NO-STACK " + filename + ' ' + line + ':' + col + ' + message;

                // log errors here or whatever you're planning on doing
                alert(msg);
            }
            catch (err)
            {

            }
        };

编辑:似乎因为stack是属性而不是方法,即使在旧浏览器上也可以安全地调用它。我仍然很困惑,因为我很确定Error.prototype以前检查对我有用,而现在却没有——所以我不确定发生了什么。

于 2015-10-03T07:09:19.747 回答
0

使用console.error(e.stack)Firefox 仅在日志中显示堆栈跟踪,Chrome 也会显示消息。如果消息包含重要信息,这可能是一个糟糕的惊喜。始终记录两者。

于 2016-01-22T13:52:45.253 回答
0

你试一试

throw new Error('some error here')

这对 chrome 非常有效:

在此处输入图像描述

于 2017-07-22T14:06:36.040 回答