【问题标题】:Is there any workaround to rethrow an exception and preserve the stacktrace in Javascript?是否有任何解决方法可以重新引发异常并在 Javascript 中保留堆栈跟踪?
【发布时间】:2012-02-18 20:38:27
【问题描述】:

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

我在 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插件可能吗?有什么解决方法或想法吗?

【问题讨论】:

  • 我能知道你为什么选择两次try...catch吗?
  • 首先,因为我需要向用户显示一条好消息,以防其中一项服务不可用。崩溃不是一种选择。其次,因为我需要将 javascript 异常的内容发送到我的后端,以确切了解发生了什么。也许这是一个错误,我想在客户打电话给我说网站不工作之前修复它。
  • 但是为什么一级 try...catch 还不够呢?是不是因为你想汇总所有的错误信息?
  • 不,这是因为我正在向异常添加更多信息。我不想以一条异常消息结束:“值是 NaN”。我想要一个更具描述性的异常,例如“从服务器返回的 invoiceId 123 金额等于 'abc',不能视为数字。”

标签: javascript google-chrome exception-handling


【解决方案1】:

在最后的catch块中尝试

    throw e.stack;

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

    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;
    }

多么奇怪的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2010-09-13
    • 2013-01-17
    • 1970-01-01
    相关资源
    最近更新 更多