-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy patherr.jl
More file actions
219 lines (193 loc) · 6.77 KB
/
err.jl
File metadata and controls
219 lines (193 loc) · 6.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
errval(::C.PyPtr) = C.PyNULL
errval(::T) where {T<:Number} = zero(T) - one(T)
iserrval(val) = val == errval(val)
iserrset() = C.PyErr_Occurred() != C.PyNULL
iserrset(val) = val == errval(val)
errcheck() = iserrset() ? pythrow() : nothing
errcheck(val) = iserrset(val) ? pythrow() : val
iserrset_ambig(val) = iserrset(val) && iserrset()
errcheck_ambig(val) = iserrset_ambig(val) ? pythrow() : val
errclear() = C.PyErr_Clear()
errmatches(t) = (@autopy t C.PyErr_ExceptionMatches(t_)) == 1
function errget()
t = Ref(C.PyNULL)
v = Ref(C.PyNULL)
b = Ref(C.PyNULL)
C.PyErr_Fetch(t, v, b)
(pynew(t[]), pynew(v[]), pynew(b[]))
end
errset(t::Py) = C.PyErr_SetNone(t)
errset(t::Py, v::Py) = C.PyErr_SetObject(t, v)
errset(t::Py, v::String) = C.PyErr_SetString(t, v)
function errnormalize!(t::Py, v::Py, b::Py)
tref = Ref(getptr(t))
vref = Ref(getptr(v))
bref = Ref(getptr(b))
C.PyErr_NormalizeException(tref, vref, bref)
setptr!(t, tref[])
setptr!(v, vref[])
setptr!(b, bref[])
(t, v, b)
end
"""
PyException(x)
Wraps the Python exception `x` as a Julia `Exception`.
"""
mutable struct PyException <: Exception
_t::Py
_v::Py
_b::Py
_isnormalized::Bool
end
function PyException(v::Py = pybuiltins.None)
if pyisnone(v)
t = b = v
elseif pyisinstance(v, pybuiltins.BaseException)
t = pytype(v)
b = pygetattr(v, "__traceback__", pybuiltins.None)
else
throw(ArgumentError("expecting a Python exception"))
end
PyException(t, v, b, true)
end
export PyException
ispy(x::PyException) = true
Py(x::PyException) = x.v
function Base.show(io::IO, x::PyException)
show(io, typeof(x))
print(io, "(")
show(io, x.v)
print(io, ")")
end
function Base.getproperty(exc::PyException, k::Symbol)
if k in (:t, :v, :b) && !exc._isnormalized
errnormalize!(exc._t, exc._v, exc._b)
pyisnull(exc._t) && pycopy!(exc._t, pybuiltins.None)
pyisnull(exc._v) && pycopy!(exc._v, pybuiltins.None)
pyisnull(exc._b) && pycopy!(exc._b, pybuiltins.None)
pyisnone(exc._v) || (exc._v.__traceback__ = exc._b)
exc._isnormalized = true
end
k == :t ? exc._t : k == :v ? exc._v : k == :b ? exc._b : getfield(exc, k)
end
pythrow() = throw(PyException(errget()..., false))
file_to_pymodule(fname::String) = begin
isfile(fname) || return nothing
modules = pyimport("sys").modules
for (n, m) in modules.items()
if pyhasattr(m, "__file__")
fname2 = pystr(String, m.__file__)
if isfile(fname2) && realpath(fname) == realpath(fname2)
return pystr(String, n)
end
end
end
end
Base.showerror(io::IO, e::PyException) = _showerror(io, e, nothing, backtrace = false)
Base.showerror(io::IO, e::PyException, bt; backtrace = true) =
_showerror(io, e, bt; backtrace = backtrace)
function _showerror(io::IO, e::PyException, bt; backtrace = true)
print(io, "Python: ")
if pyisnone(e.t)
print(io, "mysterious error (no error was actually set)")
if backtrace
Base.show_backtrace(io, bt)
end
return
end
if CONFIG.auto_sys_last_traceback
try
sys = pyimport("sys")
sys.last_type = e.t
sys.last_value = e.v
sys.last_traceback = e.b
catch err
print(io, "<error while setting 'sys.last_traceback': $err>")
end
end
if !pyisnull(pyJuliaError) && pyissubclass(e.t, pyJuliaError)
# handle Julia exceptions specially
try
je, jb = pyconvert(Tuple{Any,Any}, e.v.args)
print(io, "Julia: ")
if je isa Exception
showerror(io, je, jb, backtrace = backtrace && jb !== nothing)
else
print(io, je)
backtrace && jb !== nothing && Base.show_backtrace(io, jb)
end
catch err
println("<error while printing Julia exception inside Python exception: $err>")
end
else
# print the type name
try
print(io, e.t.__name__)
catch err
print(io, "<error while printing type: $err>")
end
# print the error message
if !pyisnone(e.v)
print(io, ": ")
try
print(io, e.v)
catch err
print(io, "<error while printing value: $err>")
end
end
end
if backtrace
# print the Python stacktrace
println(io)
printstyled(io, "Python stacktrace:")
if pyisnone(e.b)
printstyled(io, " none")
else
try
fs = [
(
pystr(String, x.name),
pystr(String, x.filename),
pystr(String, x.lineno),
) for x in pyimport("traceback").extract_tb(e.b)
]
mcdict = Dict{String,Symbol}()
mccyclyer =
Iterators.Stateful(Iterators.cycle(Base.STACKTRACE_MODULECOLORS))
# skip a couple as a basic attempt to make the colours different from the Julia stacktrace
popfirst!(mccyclyer)
popfirst!(mccyclyer)
for (i, (name, fname, lineno)) in enumerate(reverse(fs))
println(io)
printstyled(io, " [", i, "] ")
printstyled(io, name, bold = true)
println(io)
printstyled(io, " @ ", color = :light_black)
mod = file_to_pymodule(fname)
if mod !== nothing
# print the module, with colour determined by the top level name
tmod = first(split(mod, ".", limit = 2))
color = get!(mcdict, tmod) do
popfirst!(mccyclyer)
end
printstyled(io, mod, " ", color = color)
end
if isfile(fname) &&
:stacktrace_contract_userdir in names(Base, all = true) &&
Base.stacktrace_contract_userdir()
if :replaceuserpath in names(Base, all = true)
fname = Base.replaceuserpath(fname)
elseif :contractuser in names(Base.Filesystem, all = true)
fname = Base.Filesystem.contractuser(fname)
end
end
printstyled(io, fname, ":", lineno, color = :light_black)
end
catch err
print(io, "<error while printing stacktrace: $err>")
end
end
# print the Julia stacktrace
Base.show_backtrace(io, bt)
end
end