Created
August 14, 2018 10:00
-
-
Save headsrooms/07e40d1b261695a3ce61228aeb5e4390 to your computer and use it in GitHub Desktop.
Manage python exceptions through decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@contextmanager | |
def avoid( | |
exception: type(Exception), | |
raises: Exception = None, | |
exception_manager: Callable = None, | |
finally_manager: Callable = lambda: (), | |
): | |
try: | |
yield | |
except exception as e: | |
if raises: | |
raise raises | |
if exception_manager: | |
exception_manager(e) | |
finally: | |
finally_manager() | |
def manager_function(e): | |
print(f'Se lanzo la excepción {repr(e)}') | |
@avoid(AttributeError, raises=Exception('Fallo en prueba')) | |
def prueba(): | |
raise AttributeError('333') | |
@avoid(AttributeError, exception_manager=manager_function) | |
def prueba_2(): | |
raise AttributeError('333') | |
@avoid( | |
AttributeError, | |
finally_manager=lambda: print('pues al final se ha quedado buena tarde'), | |
) | |
def prueba_3(): | |
raise AttributeError('333') | |
with avoid(Exception): | |
prueba() | |
prueba_2() | |
prueba_3() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment