I have difficulty finding a โpythonicโ way to do this: I need to catch different blocks of code with the same try-except pattern. The catch blocks are different from each other. I am currently repeating the same try-except pattern at multiple points in the code with a long list of exceptions.
try:
block to catch
except E1, e:
log and do something
except E2, e:
log and do something
...
except Exception, e:
log and do something
There is a good way to solve this problem using the with statement and the context manager decoder:
from contextlib import contextmanager
@contextmanager
def error_handler():
try:
yield
except E1, e:
log and do something
...
except Exception, e:
log and do something
...
with error_handler():
block to catch
...
But what happens if I need to know if there was an exception in the block? those. Is there any alternative to doing something like the previous one with a block for try-except-else?
Usage example:
for var in vars:
try:
block to catch
except E1, e:
log and do something
except E2, e:
log and do something
...
except Exception, e:
log and do something
else:
do something else
Can I do something similar in pythonic to avoid repeating the same try-except pattern over and over again?