@@ -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):
@@ -262,14 +271,17 @@ def _add_context_to_exception(
262271 }
263272 context_parts = _build_context_parts (final_context_object , final_context )
264273 context_message = _create_context_box (context_parts )
265- _store_context_attributes (
266- original_error , final_context_object , final_context , original_message
267- )
274+ if type (original_error ) == KeyError :
275+ f = ExtKeyError (original_message )
276+ else :
277+ f = original_error
278+ _store_context_attributes (f , final_context_object , final_context , original_message )
268279 if context_parts :
269280 formatted_message = f"\n { context_message } \n \n { original_message } "
270- original_error .args = (formatted_message ,)
281+ f .args = (formatted_message ,)
271282 else :
272- original_error .args = (original_message ,)
283+ f .args = (original_message ,)
284+ return f
273285
274286
275287@contextmanager
@@ -298,7 +310,5 @@ def error_context(context_object: Any = None, **context):
298310 try :
299311 yield
300312 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
313+ f = _add_context_to_exception (e , context_object , ** context )
314+ raise f from None
0 commit comments