Skip to content

Instantly share code, notes, and snippets.

@BoZenKhaa
Created July 11, 2022 22:00
Show Gist options
  • Save BoZenKhaa/5f5ad1b2477bab9b6a96c0b3b8ad9243 to your computer and use it in GitHub Desktop.
Save BoZenKhaa/5f5ad1b2477bab9b6a96c0b3b8ad9243 to your computer and use it in GitHub Desktop.
"""
serror(error::Exception) -> String
Get error and stacktrace as String, e.g. for use in warning.
Useful in Jypyter notebooks where error messages are not displayed correctly (https://github.com/JuliaLang/IJulia.jl/issues/1043)
Example:
```julia
julia> try
a=b
catch e
@warn "Oh no, exception:\n \$(serror(e))"
end
┌ Warning: Oh no, exception:
│ UndefVarError: b not defined
│ 13-element Vector{Base.StackTraces.StackFrame}:
│ top-level scope at REPL[7]:2
│ eval at boot.jl:373 [inlined]
│ eval_user_input(ast::Any, backend::REPL.REPLBackend) at REPL.jl:150
│ repl_backend_loop(backend::REPL.REPLBackend) at REPL.jl:246
│ start_repl_backend(backend::REPL.REPLBackend, consumer::Any) at REPL.jl:231
│ run_repl(repl::REPL.AbstractREPL, consumer::Any; backend_on_current_task::Bool) at REPL.jl:364
│ run_repl(repl::REPL.AbstractREPL, consumer::Any) at REPL.jl:351
│ (::Base.var"#930#932"{Bool, Bool, Bool})(REPL::Module) at client.jl:394
│ #invokelatest#2 at essentials.jl:716 [inlined]
│ invokelatest at essentials.jl:714 [inlined]
│ run_main_repl(interactive::Bool, quiet::Bool, banner::Bool, history_file::Bool, color_set::Bool) at client.jl:379
│ exec_options(opts::Base.JLOptions) at client.jl:309
│ _start() at client.jl:495
└ @ Main REPL[7]:4
```
"""
function serror(error::Exception)
error_msg = sprint(showerror, error)
st = sprint((io,v) -> show(io, "text/plain", v), stacktrace(catch_backtrace()))
return "$error_msg\n$st"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment