是否有任何解决方法来重新抛出异常并在Javascript中保留堆栈跟踪?

时间:2012-01-25 16:44:23

标签: javascript google-chrome exception-handling

我知道在Javascript中重新抛出异常时,Chrome有known bug不保留堆栈跟踪。

我在Chrome中运行了以下代码:

try {
    try {
      runCodeThatMayThrowAnException();
    } catch (e) {
        // I'm handing the exception here (displaying a nice message or whatever)
        // Now I want to rethrow the exception
        throw (e);
    }
} catch (e) {
    // The stacktrace was lost here :(
}

有没有办法保持堆栈跟踪?一个jQuery插件可能吗?任何变通方法或想法?

1 个答案:

答案 0 :(得分:5)

在最后的捕捉区块尝试

    throw e.stack;

我的意思是最后一个(进入浏览器的那个)。如果您将try / catch嵌套得更深,则需要更改先前的抛出。

    function throwError() {
        var test = _undefined.propertyAccess;
    }
    try {
        try {
            try {
                throwError();
            } catch (e) {
                alert("exception: " + e.stack);
                throw e;
            }
        } catch (e) {
            console.log(e.stack);
            throw e;
        }
    } catch (e) {
        throw e.stack;
    }

多么奇怪的错误。