Getting error message from tenacity retry_state.outcome.result() results in program termination

620 views Asked by At

I'm using the python tenacity library to do exponential backoff of a funtion.

import tenacity

def log_attempt_number(retry_state):
    print(f"Retrying: {retry_state.attempt_number}...")
    print(retry_state.outcome)

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(100), after=log_attempt_number)
def throw_exception():
    throw Exception("What is this exception?")

This code gives me:

Retrying: 1...
<Future at 0x7feeaf6354c0 state=finished raised Exception>
Retrying: 2...
<Future at 0x7feeaf401580 state=finished raised Exception>
Retrying: 3...
<Future at 0x7feeaf6354c0 state=finished raised Exception>
Retrying: 4...
<Future at 0x7feeaf401580 state=finished raised Exception>
Retrying: 5...
<Future at 0x7feeaf6354c0 state=finished raised Exception>

...

But I want to see the error message, not the Future object. On their website, all I can see as an option to get the error message is the function result() which gives me the error message and then terminates.

def log_attempt_number(retry_state):
    print(f"Retrying: {retry_state.attempt_number}...")
    print(retry_state.outcome.result()) #This function terminates the program

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(100), 
after=log_attempt_number)
def throw_exception():
    throw Exception("What is this exception?")

...

Retrying: 1...
What is this Exception?
worryword@WorryWord:~/Development/SOTests$

So my question is: how do I get the error message without terminating the program? I have an issue where the first error is not necessarily the 10th error, etc.

1

There are 1 answers

0
Ben Alan On BEST ANSWER

As a workaround, I used a try-except like so:

try:
    retry_state.outcome.result()
except Exception as e:
    print(e)

This gives you the exception without terminating the program.