Rostislav Aleev
Rostislav Aleev

Reputation: 371

tenacity retrying with exception handler

Can tenacity handle this or should I implement retry wrapper myself if I need to catch exception do a callback and get back to next try?

send → fetch error → if recoverable → run callback → try send again

When I use a simple case with this code, next try never happened:

class A:
    a = 0
 
    @retry(stop=stop_after_attempt(7))
    def never_give_up_never_surrender(cls):
        try:
            1/cls.a
            print('possibly wrong')
        except ZeroDivisionError:
            cls.a+=1
            print('next try')
        else:
            print('done')

Upvotes: 3

Views: 3796

Answers (1)

Rostislav Aleev
Rostislav Aleev

Reputation: 371

There is a way:

def error_callback(retry_state):
   # error handler
   if isinstance(retry_state.outcome.exception(), ZeroDivisionError):
     print("Can't handle it")
   else:
     print("Handled")


@retry(retry_error_callback=error_callback)
def zero_division():
  a = 1 
  b = 0
  a/b

It's not obviously described in documentation but in API.

Upvotes: 2

Related Questions