如何在捕获异常后用Erlang编写异常堆栈跟踪?

kb5ga3dv  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(287)

假设我有这样的东西:

try code_that_fails()
catch _:_ -> .....

如何在catch块中打印堆栈跟踪?该块捕获所有异常,但我不知道如何打印堆栈...
你能帮我吗?

hwamh0ep

hwamh0ep1#

从Erlang 21.0开始,有了一种新的官方方法来获取堆栈跟踪。在异常的第三个参数上的try表达式中有一个可选的模式匹配,它将包含堆栈跟踪:

try
   code_that_fails()
catch
   _:_:Stacktrace ->
      erlang:display(Stacktrace)
end

旧版本(OTP 20及以下版本)

对于Erlang/OTP 20及以下版本,您需要使用get_stacktrace/0,它允许您获取调用进程中最后一个异常的堆栈跟踪:

try
   code_that_fails()
catch
   _:_ ->
      erlang:display(erlang:get_stacktrace())
end
nkcskrwz

nkcskrwz2#

您问题的答案是:

io:format("Backtrace ~p~n", [erlang:get_stacktrace()])

当前函数位于列表的开头。请阅读man 3erl erlang或erlang:get_stacktrace/0中的更多内容

vd8tlhqk

vd8tlhqk3#

In your example, you don't need the try ; you can just do

result = (catch code_that_fails()).

If 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 original catch 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.

相关问题