Custom Retry behaviour per each error with tenacity library

443 views Asked by At

I would like to make a custom retry behaviour for different error types. For example if I receive a 401 Error I would like to call a token refresh before retring a request. If I receive a 500 I would like to retry the error after some time. etc.

Is this achievable with the tenacity library? https://tenacity.readthedocs.io/en/latest/

1

There are 1 answers

0
Matmozaur On

if you want to use tenacity library, you can use retry_if_exception_type method: https://tenacity.readthedocs.io/en/stable/api.html#tenacity.retry.retry_if_exception_type

Although I think that custom decorator also can be a good option if you want to be really flexible, e.g.:

def custom_retry(f):
    def wrapper(*args, **kw):
        try:
            return f(*args, **kw)
        except AttributeError as ae:
            [Do smth]
        except KeyError as ke:
            [Do smth else]
    return wrapper