channable / opnieuw

One weird trick to make your code more reliable

Home Page:https://tech.channable.com/posts/2020-02-05-opnieuw.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Works in Try block?

jaoxford opened this issue · comments

Hi there,

I'm curious to know if this library will work when a function is called from within a try block?
If an exception happens inside the function being called will the except block be called, or only if the retries happen to fail?

try:
    foo()
except Exception:
    print(Exception)

@retry(
    retry_on_exceptions=(FooException),
    max_calls_total=3,
    retry_window_after_first_call_in_seconds=60,
)
def foo():

This pattern is used in the testcases.

class TestRetryDecorator(unittest.TestCase):
counter = 0
@retry(
retry_on_exceptions=TypeError,
max_calls_total=3,
retry_window_after_first_call_in_seconds=3,
)
def foo(self) -> None:
self.counter += 1
raise TypeError
def test_raise_exception(self):
try:
self.foo()
except TypeError as e:
self.assertTrue(isinstance(e, TypeError))
def test_retry_times(self):
start = time.time()
self.counter = 0
try:
self.foo()
except TypeError as e:
end = time.time()
t_diff = end - start
self.assertGreater(t_diff, 1)
self.assertEqual(self.counter, 3)

As we can see from the assert statements the counter is incremented to 3 before the block in the except statement is called.

If you want to log the exceptions that occur in foo they should be logged from the inside.

@retry(
    retry_on_exceptions=(FooException),
    max_calls_total=3,
    retry_window_after_first_call_in_seconds=60,
)
def wrap_foo:
	try:
		foo()
	except Exception as e:
		log(e)
		raise e

def foo:
	pass

Lovely, thank you!