I am trying to wrap my head around how to write a context manager that deals with writing some logs while handling any exceptions. The problem I am trying to solve is to make code like this:
try:
# code that can raise exception here
except Exception as e:
print('failed', e)
print('all good')
This is a repeated pattern I have in the code and I think it's best handled with a context manager like:
with my_ctx_manager(success_msg='all good', failed_msg='failed):
# code that can raise exception here
this looks much better, but I don't know how to write the actual context manager to deal with any exceptions that could rise inside the context.
@contextlib.contextmanager
def my_ctx_manager(success_msg, failed_msg):
try:
# if no exception then print(success_msg)
# How do I catch any exception here
except Exception:
print(failed_msg)
# I need the exception to propagate as well
raise
I guess my question is more of the type: How do I make sure that the context manager correctly catches, logs and re-raise any exception for the code that is wrapping ?