@@ -135,6 +135,28 @@ _PyErr_GetTopmostException(PyThreadState *tstate)
135
135
return exc_info ;
136
136
}
137
137
138
+ static PyObject *
139
+ get_normalization_failure_note (PyThreadState * tstate , PyObject * exception , PyObject * value )
140
+ {
141
+ PyObject * args = PyObject_Repr (value );
142
+ if (args == NULL ) {
143
+ _PyErr_Clear (tstate );
144
+ args = PyUnicode_FromFormat ("<unknown>" );
145
+ }
146
+ PyObject * note ;
147
+ const char * tpname = ((PyTypeObject * )exception )-> tp_name ;
148
+ if (args == NULL ) {
149
+ _PyErr_Clear (tstate );
150
+ note = PyUnicode_FromFormat ("Normalization failed: type=%s" , tpname );
151
+ }
152
+ else {
153
+ note = PyUnicode_FromFormat ("Normalization failed: type=%s args=%S" ,
154
+ tpname , args );
155
+ Py_DECREF (args );
156
+ }
157
+ return note ;
158
+ }
159
+
138
160
void
139
161
_PyErr_SetObject (PyThreadState * tstate , PyObject * exception , PyObject * value )
140
162
{
@@ -160,19 +182,27 @@ _PyErr_SetObject(PyThreadState *tstate, PyObject *exception, PyObject *value)
160
182
Py_XINCREF (value );
161
183
if (!is_subclass ) {
162
184
/* We must normalize the value right now */
163
- PyObject * fixed_value ;
164
185
165
186
/* Issue #23571: functions must not be called with an
166
187
exception set */
167
188
_PyErr_Clear (tstate );
168
189
169
- fixed_value = _PyErr_CreateException (exception , value );
170
- Py_XDECREF (value );
190
+ PyObject * fixed_value = _PyErr_CreateException (exception , value );
171
191
if (fixed_value == NULL ) {
192
+ PyObject * exc = _PyErr_GetRaisedException (tstate );
193
+ assert (PyExceptionInstance_Check (exc ));
194
+
195
+ PyObject * note = get_normalization_failure_note (tstate , exception , value );
196
+ Py_XDECREF (value );
197
+ if (note != NULL ) {
198
+ /* ignore errors in _PyException_AddNote - they will be overwritten below */
199
+ _PyException_AddNote (exc , note );
200
+ Py_DECREF (note );
201
+ }
202
+ _PyErr_SetRaisedException (tstate , exc );
172
203
return ;
173
204
}
174
-
175
- value = fixed_value ;
205
+ Py_XSETREF (value , fixed_value );
176
206
}
177
207
178
208
exc_value = _PyErr_GetTopmostException (tstate )-> exc_value ;
0 commit comments