Alex Craft
Alex Craft

Reputation: 15406

How to print full stack trace of an Error?

println not printing stack trace, this code

try
  eval(Meta.parse("invalidfn()"))
catch error
  println(error)
end

produces

UndefVarError(:invalidfn)

And error.msg or fieldnames(error) are not working.

Upvotes: 14

Views: 2403

Answers (1)

giordano
giordano

Reputation: 8344

You can use catch_backtrace, together with the @error macro from the Logging standard library:

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

As an alternative, you can directly call the (undocumented) three-argument 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

Upvotes: 21

Related Questions