2

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')
martineau
  • 119,623
  • 25
  • 170
  • 301
Rostislav Aleev
  • 351
  • 5
  • 19
  • I know nothing about 'tenacity', but how's it supposed to know to retry? It looks to me that if you catch an exception and print something out, then you've handled the exception and there's nothing to be retried. – guest Dec 18 '20 at 20:10
  • @guest: From tenacity's [documentation](https://tenacity.readthedocs.io/en/latest/) it looks like it does its magic via the `@retry` decorator. – martineau Dec 18 '20 at 20:29
  • Sure, but there's no difference in outcome of the method regardless of whether a ZeroDivisionError is thrown or not. Either way, never_give_up... does a normal return. – guest Jan 05 '21 at 19:22
  • Try adding a 'throw' after printing 'next try' – guest Jan 05 '21 at 19:23

1 Answers1

2

There is a way:

def error_callback(retry_state):
   # error handler
   if isinstance(retry_state._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.

Rostislav Aleev
  • 351
  • 5
  • 19