捕获异常后如何在 erlang 中编写异常堆栈跟踪?
假设我有这样的事情:
try code_that_fails()
catch _:_ -> .....
如何在 catch 块中打印堆栈跟踪?该块捕获所有异常,但我不知道如何打印堆栈......
你能帮助我吗?
Suppose I have something like this :
try code_that_fails()
catch _:_ -> .....
How do I print the stacktrace in the catch block? That block catches all exceptions, but I don't know how to print the stack...
Can you help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 Erlang 21.0 开始,有一种新的官方方法来获取堆栈跟踪。异常中第三个参数的 try 表达式 中的可选模式匹配,其中将包含堆栈跟踪:
旧版本(OTP 20 及以下)
对于 Erlang/OTP 20 及以下版本,您需要使用 get_stacktrace/0,它允许您获取调用过程中最后一个异常的堆栈跟踪:
From Erlang 21.0 onwards, there's a new official way to get the stack trace. An optional pattern match in the try expression on the third parameter in the exception, which will contain the stack trace:
Older versions (OTP 20 and below)
For versions of Erlang/OTP 20 and below, you need to use get_stacktrace/0, which allows you to get the stacktrace of the last exception in the calling process:
您的问题的答案是:
当前函数位于列表的开头。阅读
man 3erl erlang
或 erlang:get_stacktrace/ 了解更多信息0An answer for your question is:
The current function is at the head of the list. Read more in
man 3erl erlang
or erlang:get_stacktrace/0在您的示例中,您不需要
try
; 组如果引发异常,
catch
返回一个包含 错误代码和堆栈跟踪。请注意,这通常被认为是不好的做法,因为它可以掩盖异常。另一个答案中描述的堆栈跟踪方法几乎肯定是您想要的。
try
是原始catch
功能的扩展;如果使用它,则需要为要捕获的每种异常类型指定子句,并适当地处理它们。有关详细信息和清晰的示例,请参阅 Erlang 参考手册的第 6.18/6.19 节。In your example, you don't need the
try
; you can just doIf an exception is raised,
catch
returns a tuple that contains the error code and stack trace.Note that this is generally considered bad practice as it can mask exceptions. The stacktrace approach described in another answer is almost certainly what you want.
try
is an extension of the originalcatch
functionality; if you use it, you need to specify clauses for each exception type you would like to catch, and handle them appropriately. See sections 6.18/6.19 of the Erlang reference manual for details and clear examples.