@@ -109,7 +109,7 @@ def _get_existing_context(error: Exception):
109
109
existing ["context_object" ],
110
110
existing ["context" ],
111
111
)
112
- return str (error ), None , {}
112
+ return error . original_error if type ( error ) == ExtKeyError else str (error ), None , {}
113
113
114
114
115
115
def _format_object_context (obj : Any ) -> Optional [str ]:
@@ -239,13 +239,22 @@ def _store_context_attributes(
239
239
"original_message" : original_message ,
240
240
}
241
241
try :
242
- error .original_error = type (error )(original_message )
242
+ error .original_error = (
243
+ original_message
244
+ if type (error ) == KeyError
245
+ else type (error )(original_message )
246
+ )
243
247
except (TypeError , ValueError ):
244
248
error .original_error = Exception (original_message )
245
249
error .context_object = context_object
246
250
error .context = context
247
251
248
252
253
+ class ExtKeyError (KeyError ):
254
+ def __str__ (self ):
255
+ return "\n " + self .args [0 ]
256
+
257
+
249
258
def _add_context_to_exception (
250
259
original_error : Exception , context_object : Any = None , ** context
251
260
):
@@ -270,6 +279,13 @@ def _add_context_to_exception(
270
279
original_error .args = (formatted_message ,)
271
280
else :
272
281
original_error .args = (original_message ,)
282
+ if type (original_error ) == KeyError :
283
+ f = ExtKeyError (original_error .args [0 ])
284
+ f .original_error = original_error .original_error
285
+ f .context_object = original_error .context_object
286
+ f .context = original_error .context
287
+ return f
288
+ return original_error
273
289
274
290
275
291
@contextmanager
@@ -298,7 +314,5 @@ def error_context(context_object: Any = None, **context):
298
314
try :
299
315
yield
300
316
except Exception as e :
301
- if e .__class__ .__name__ == "KeyError" :
302
- e = RuntimeError (e .__class__ .__name__ + ": '" + e .args [0 ] + "'" )
303
- _add_context_to_exception (e , context_object , ** context )
304
- raise e
317
+ f = _add_context_to_exception (e , context_object , ** context )
318
+ raise f from None
0 commit comments