Stream: helpdesk (published)

Topic: Capture and print error as it appears in the repl


view this post on Zulip Mason Protter (Apr 25 2021 at 22:36):

In the repl, if I do 1 + "hi" I get the error message

julia> 1 + "hi"
ERROR: MethodError: no method matching +(::Int64, ::String)
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:560
  +(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} at int.jl:87
  +(::Union{Int16, Int32, Int64, Int8}, ::BigInt) at gmp.jl:534
  ...
Stacktrace:
 [1] top-level scope
   @ REPL[15]:1

If I were to wrap this in a try block, what would I have to print to stdout to make all the same info appear? I want to print the error message, the closest candidates info, and the stacktrace the way they appear in the REPL.

view this post on Zulip Mason Protter (Apr 25 2021 at 22:37):

e.g. I want to know the f such that

try
    1 + "hi"
catch e;
    f(e)
end

will print

ERROR: MethodError: no method matching +(::Int64, ::String)
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:560
  +(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} at int.jl:87
  +(::Union{Int16, Int32, Int64, Int8}, ::BigInt) at gmp.jl:534
  ...
Stacktrace:
 [1] top-level scope
   @ REPL[15]:1

view this post on Zulip Kirill Simonov (Apr 25 2021 at 23:01):

Base.display_error(e, catch_backtrace()) seems to work for me.

view this post on Zulip Mason Protter (Apr 25 2021 at 23:12):

Awesome, thanks! I knew there was something like this floating around

view this post on Zulip Takafumi Arakaki (tkf) (Apr 25 2021 at 23:16):

If you want a public API to do something similar:

try
    1 + "hi"
catch e;
    @error "got an error" exception = (e, catch_backtrace())
end

view this post on Zulip Mosè Giordano (Apr 26 2021 at 01:14):

https://stackoverflow.com/a/59690947/2442087

view this post on Zulip Mason Protter (Apr 26 2021 at 01:31):

Great, thank you both

view this post on Zulip Fredrik Ekre (Apr 26 2021 at 20:12):

See also https://julialang.zulipchat.com/#narrow/stream/274208-helpdesk-.28published.29/topic/filtering.20backtraces (for filtering like the REPL).


Last updated: Nov 06 2024 at 04:40 UTC