如何打印错误的完整堆栈跟踪?

Ale*_*hin 10 julia

println不打印堆栈跟踪,这段代码

try
  eval(Meta.parse("invalidfn()"))
catch error
  println(error)
end
Run Code Online (Sandbox Code Playgroud)

产生

UndefVarError(:invalidfn)
Run Code Online (Sandbox Code Playgroud)

error.msgfieldnames(error)不工作。

gio*_*ano 15

您可以将catch_backtrace, 与标准库@error中的宏一起使用:Logging

julia> try
         eval(Meta.parse("invalidfn()"))
       catch e
         @error "Something went wrong" exception=(e, catch_backtrace())
       end
? Error: Something went wrong
?   exception =
?    UndefVarError: invalidfn not defined
?    Stacktrace:
?     [1] top-level scope at REPL[1]:1
?     [2] eval at ./boot.jl:330 [inlined]
?     [3] eval(::Expr) at ./client.jl:425
?     [4] top-level scope at REPL[1]:2
?     [5] eval(::Module, ::Any) at ./boot.jl:330
?     [6] eval_user_input(::Any, ::REPL.REPLBackend) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:86
?     [7] macro expansion at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:118 [inlined]
?     [8] (::REPL.var"#26#27"{REPL.REPLBackend})() at ./task.jl:333
? @ Main REPL[1]:4
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以直接调用(未记录的)三参数showerror

julia> try
         eval(Meta.parse("invalidfn()"))
       catch e
         showerror(stdout, e, catch_backtrace())
       end
UndefVarError: invalidfn not defined
Stacktrace:
 [1] top-level scope at REPL[1]:1
 [2] eval at ./boot.jl:330 [inlined]
 [3] eval(::Expr) at ./client.jl:425
 [4] top-level scope at REPL[1]:2
 [5] eval(::Module, ::Any) at ./boot.jl:330
 [6] eval_user_input(::Any, ::REPL.REPLBackend) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:86
 [7] macro expansion at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/REPL/src/REPL.jl:118 [inlined]
 [8] (::REPL.var"#26#27"{REPL.REPLBackend})() at ./task.jl:333
Run Code Online (Sandbox Code Playgroud)

  • 如果你在 catch 中 `throw(e)` 我认为这与“做正常的事情”是一样的。 (3认同)