@@ -69,14 +69,19 @@ internal static Exception ThrowLastAsClrException()
69
69
Runtime . PyErr_Fetch ( out var type , out var value , out var traceback ) ;
70
70
try
71
71
{
72
- var clrObject = ManagedType . GetManagedObject ( value ) as CLRObject ;
73
72
#if NETSTANDARD
74
- if ( clrObject ? . inst is ExceptionDispatchInfo storedException )
73
+ if ( ! value . IsNull ( ) )
75
74
{
76
- storedException . Throw ( ) ;
77
- throw storedException . SourceException ; // unreachable
75
+ var exceptionInfo = TryGetDispatchInfo ( value ) ;
76
+ if ( exceptionInfo != null )
77
+ {
78
+ exceptionInfo . Throw ( ) ;
79
+ throw exceptionInfo . SourceException ; // unreachable
80
+ }
78
81
}
79
82
#endif
83
+
84
+ var clrObject = ManagedType . GetManagedObject ( value ) as CLRObject ;
80
85
if ( clrObject ? . inst is Exception e )
81
86
{
82
87
throw e ;
@@ -98,6 +103,37 @@ internal static Exception ThrowLastAsClrException()
98
103
}
99
104
}
100
105
106
+ #if NETSTANDARD
107
+ static ExceptionDispatchInfo TryGetDispatchInfo ( BorrowedReference exception )
108
+ {
109
+ if ( exception . IsNull ) return null ;
110
+
111
+ var pyInfo = Runtime . PyObject_GetAttrString ( exception , Exceptions . DispatchInfoAttribute ) ;
112
+ if ( pyInfo . IsNull ( ) )
113
+ {
114
+ if ( Exceptions . ExceptionMatches ( Exceptions . AttributeError ) )
115
+ {
116
+ Exceptions . Clear ( ) ;
117
+ }
118
+ return null ;
119
+ }
120
+
121
+ try
122
+ {
123
+ if ( Converter . ToManagedValue ( pyInfo , typeof ( ExceptionDispatchInfo ) , out object result , setError : false ) )
124
+ {
125
+ return ( ExceptionDispatchInfo ) result ;
126
+ }
127
+
128
+ return null ;
129
+ }
130
+ finally
131
+ {
132
+ pyInfo . Dispose ( ) ;
133
+ }
134
+ }
135
+ #endif
136
+
101
137
/// <summary>
102
138
/// Requires lock to be acquired elsewhere
103
139
/// </summary>
@@ -106,19 +142,20 @@ static Exception FromPyErr(BorrowedReference typeHandle, BorrowedReference value
106
142
Exception inner = null ;
107
143
string pythonTypeName = null , msg = "" , tracebackText = null ;
108
144
109
- var clrObject = ManagedType . GetManagedObject ( valueHandle ) as CLRObject ;
110
- if ( clrObject ? . inst is Exception e )
111
- {
112
- return e ;
113
- }
114
-
115
145
#if NETSTANDARD
116
- if ( clrObject ? . inst is ExceptionDispatchInfo exceptionDispatchInfo )
146
+ var exceptionDispatchInfo = TryGetDispatchInfo ( valueHandle ) ;
147
+ if ( exceptionDispatchInfo != null )
117
148
{
118
149
return exceptionDispatchInfo . SourceException ;
119
150
}
120
151
#endif
121
152
153
+ var clrObject = ManagedType . GetManagedObject ( valueHandle ) as CLRObject ;
154
+ if ( clrObject ? . inst is Exception e )
155
+ {
156
+ return e ;
157
+ }
158
+
122
159
var type = PyObject . FromNullableReference ( typeHandle ) ;
123
160
var value = PyObject . FromNullableReference ( valueHandle ) ;
124
161
var traceback = PyObject . FromNullableReference ( tracebackHandle ) ;
0 commit comments