Say I want to reraise an exception with extra information for handling – what would be the best practice for that?
I came up with the following but it smells fishy to me:
<code>def internal_function():
raise ValueError("smelly socks!")
def context_function():
try:
internal_function()
except Exception as e:
e.args= e.args[:1] + ("<raise_context>",) + e.args[1:] # raise context varies on conditions ofc
raise e
def handler_function():
try:
context_function()
except Exception as e:
msg, context, *other = e.args
if context == "some_context":
pass # handle one way
elif context == "some other context":
pass # handle another way
</code>
<code>def internal_function():
raise ValueError("smelly socks!")
def context_function():
try:
internal_function()
except Exception as e:
e.args= e.args[:1] + ("<raise_context>",) + e.args[1:] # raise context varies on conditions ofc
raise e
def handler_function():
try:
context_function()
except Exception as e:
msg, context, *other = e.args
if context == "some_context":
pass # handle one way
elif context == "some other context":
pass # handle another way
</code>
def internal_function():
raise ValueError("smelly socks!")
def context_function():
try:
internal_function()
except Exception as e:
e.args= e.args[:1] + ("<raise_context>",) + e.args[1:] # raise context varies on conditions ofc
raise e
def handler_function():
try:
context_function()
except Exception as e:
msg, context, *other = e.args
if context == "some_context":
pass # handle one way
elif context == "some other context":
pass # handle another way
FYI, not a duplicate of How can I add context to an exception in Python, since there the poster wants to amend the message string rather than adding separate metadata.