Is there any workaround to rethrow an exception and preserve the stacktrace in Javascript?

半世苍凉 提交于 2019-12-08 22:00:32

问题


I know that Chrome has a known bug not preserving the stacktrace when rethrowing an exception in Javascript.

I have the following code running in 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 :(
}

Is there any way to keep the stacktrace? A jQuery plug-in maybe? Any workaround or ideas?


回答1:


In the final catch block try

    throw e.stack;

And I mean the very last one (the one going to the browser). If you nest your try/catch deeper, you'd need to change your previous 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;
    }

What an odd bug.



来源:https://stackoverflow.com/questions/9006490/is-there-any-workaround-to-rethrow-an-exception-and-preserve-the-stacktrace-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!