@@ -109,7 +109,7 @@ def _get_existing_context(error: Exception):
109109 existing ["context_object" ],
110110 existing ["context" ],
111111 )
112- return str (error ), None , {}
112+ return error . original_error if type ( error ) == ExtKeyError else str (error ), None , {}
113113
114114
115115def _format_object_context (obj : Any ) -> Optional [str ]:
@@ -239,13 +239,22 @@ def _store_context_attributes(
239239 "original_message" : original_message ,
240240 }
241241 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+ )
243247 except (TypeError , ValueError ):
244248 error .original_error = Exception (original_message )
245249 error .context_object = context_object
246250 error .context = context
247251
248252
253+ class ExtKeyError (KeyError ):
254+ def __str__ (self ):
255+ return "\n " + self .args [0 ]
256+
257+
249258def _add_context_to_exception (
250259 original_error : Exception , context_object : Any = None , ** context
251260):
@@ -270,6 +279,13 @@ def _add_context_to_exception(
270279 original_error .args = (formatted_message ,)
271280 else :
272281 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
273289
274290
275291@contextmanager
@@ -298,7 +314,5 @@ def error_context(context_object: Any = None, **context):
298314 try :
299315 yield
300316 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