JuliaLang / Compat.jl

Compatibility across Julia versions
Other
144 stars 117 forks source link

current_exceptions implementation fails when backtrace=false #757

Closed Sacha0 closed 2 years ago

Sacha0 commented 2 years ago

746 introduced support for current_exceptions (née catch_stack), which bears a backtrace keyword argument. When backtrace=false, the returned ExceptionStack's stack field should be a Vector of NamedTuples where the second (backtrace) element of each tuple is nothing. Instead the Compat implementation throws, e.g. on Julia 1.6.2:

julia> using Compat: current_exceptions

julia> try
           throw(UndefVarError(:cat))
       catch
           current_exceptions(;backtrace=false)
       end
ERROR: MethodError: no method matching getindex(::UndefVarError, ::Int64)
Stacktrace:
 [1] current_exceptions(task::Task; backtrace::Bool)
   @ Compat ~/pkg/Compat.jl/src/Compat.jl:1105
 [2] top-level scope
   @ REPL[7]:4

caused by: UndefVarError: cat not defined
Stacktrace:
 [1] top-level scope
   @ REPL[7]:2

The trick is that the implementation

function current_exceptions(task=current_task(); backtrace=true)
    stack = Base.catch_stack(task, include_bt=backtrace)
    ExceptionStack(Any[(exception=x[1],backtrace=x[2]) for x in stack])
end

passes the backtrace kwarg through to catch_stack which, when include_bt=false, emits a Vector of exceptions, rather than a Vector of two-tuples (exception-backtrace pairs). The array comprehension on the next line expects a Vector of two-tuples, though, and consequently ends up attempting to index into exceptions.

Patch inbound :).