Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class RetryExhaust(Exception):
- pass
- def retry(tries:int=1, error_handler:object = None):
- def wrapper(function):
- def wrapped(*args, **kwargs):
- counter = 1
- retry = True
- while retry and tries >= counter:
- if tries == 1:
- try:
- return function(*args, **kwargs)
- except Exception as e:
- if counter <=tries:
- if error_handler:
- retry = error_handler(e)
- else:
- retry = False
- raise e
- elif tries > 1:
- try:
- return function(*args, **kwargs)
- except Exception as e:
- if counter <tries:
- if error_handler:
- retry = error_handler(e)
- if retry:
- counter +=1
- else:
- retry = False
- else:
- counter +=1
- continue
- else:
- raise RetryExhaust(f'Exception: {repr(e)} , Attempts:{counter}')
- return wrapped
- return wrapper
- def test_division_handler(e:object):
- exc_type = e.__class__.__name__
- if exc_type == "ZeroDivisionError":
- print('What to do?')
- return True
- else:
- raise e
- @retry(tries=2, error_handler=None)
- def test_division(a:int=1, b:int=0):
- print(a/b)
- test_division()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement