Capture error from include_string

Consider

my_e = try
    include_string(Main, "throw(ArgumentError(\"test\"))")
catch e
    e
end

The exercise is to extract the ArgumentError("test") from my_e using public API. Is this possible?

Currently it is wrapped in a LoadError, the internal structure of which is not public API, and may change in the future. So my_e.error is not what I am looking for.

I would just do:

e isa LoadError ? e.error : e

to use e.error if it is a LoadError. We should really just document this field, since there’s no way to use LoadError without it and it has been stable for a decade now. But you’re correct that you shouldn’t assume include_string will always wrap exceptions in a LoadError.

Alternatively, since include_string is nowadays implemented in pure Julia using (it looks like) only public APIs, in principle you could re-implement it (i.e. copy-and-paste the implementation) and get rid of the LoadError.

As you noticed, there is a to-do to get rid of the LoadError for include_string in a future Julia version. Maybe this could be done in 1.x, since it’s not guaranteed by the docs and we got rid of the LoadError wrapper for macroexpand in 1.7 (julia#38379). Anyone want to file a PR?

1 Like