如何在 Javascript 中重新抛出异常,但保留堆栈?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3734236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I rethrow an exception in Javascript, but preserve the stack?
提问by Geoff
In Javascript, suppose I want to perform some cleanup when an exception happens, but let the exception continue to propagate up the stack, eg:
在 Javascript 中,假设我想在发生异常时执行一些清理,但让异常继续向上传播堆栈,例如:
try {
enterAwesomeMode();
doRiskyStuff(); // might throw an exception
} catch (e) {
leaveAwesomeMode();
throw e;
}
doMoreStuff();
leaveAwesomeMode();
The problem with this code is that catching and rethrowing the exception causes the stack trace information up to that point to be lost, so that if the exception is subsequently caught again, higher up on the stack, the stack trace only goes down to the re-throw. This sucks because it means it doesn't contain the function that actually threw the exception.
这段代码的问题在于捕获并重新抛出异常会导致到该点的堆栈跟踪信息丢失,因此如果随后再次捕获异常,在堆栈的更高位置,堆栈跟踪只会向下移动到重新-扔。这很糟糕,因为这意味着它不包含实际抛出异常的函数。
As it turns out, try..finally has the same behavior, in at least Chrome (that is, it is not the re-throw that is the problem precisely, but the presence of any exception handler block at all.)
事实证明, try..finally 具有相同的行为,至少在 Chrome 中(也就是说,问题不是重新抛出,而是任何异常处理程序块的存在。)
Does anyone know of a way to rethrow an exception in Javascript but preserve the stack trace associated with it? Failing that, how about suggestions for other ways to add exception-safe cleanup handlers, while also capturing complete stack traces when an exception happens?
有谁知道在 Javascript 中重新抛出异常但保留与之相关的堆栈跟踪的方法吗?否则,关于添加异常安全清理处理程序的其他方法的建议如何,同时在发生异常时捕获完整的堆栈跟踪?
Thanks for any pointers :)
感谢您的任何指点:)
采纳答案by Glenn Maynard
This is a bug in Chrome. Rethrowing an exception should preserve the call trace.
这是 Chrome 中的一个错误。重新抛出异常应该保留调用跟踪。
http://code.google.com/p/chromium/issues/detail?id=60240
http://code.google.com/p/chromium/issues/detail?id=60240
I don't know of any workaround.
我不知道有什么解决方法。
I don't see the problem with finally. I do see exceptions silently not showing up on the error console in some cases after a finally, but that one seems to be fixed in development builds.
我没有看到 finally 的问题。在某些情况下,在 finally 之后,我确实看到异常没有出现在错误控制台上,但似乎在开发版本中已修复。
回答by Mike Stay
The stack property of an Error object is created at the same time as the Error object itself, not at the point it's thrown. They're often the same because of the idiom
Error 对象的 stack 属性与 Error 对象本身是同时创建的,而不是在它被抛出的时候。由于习语,它们通常是相同的
throw new Error("message");
and if you use the code just as you've written it, the stack property will notbe changed when you rethrow the error.
并且如果您按照您编写的代码使用代码,则当您重新抛出错误时,stack 属性不会更改。