tenacity
tenacity copied to clipboard
Re-raising RetryError from retry_error_callback
Hi all,
Say I want to log if a function does not succeed after all retry attempts, I could implement this using a function passed to retry_error_callback. This however prevents the caller from handling RetryError as it is not raised if an error callback is provided.
Is there an elegant way to raise the RetryError that would otherwise have occurred?
Would there be any interest in the ability to raise RetryError from the retry state object, in a similar style to retry_state.outcome.exception()?
import logging
from tenacity import retry, stop_after_attempt
def on_error(retry_state):
logging.exception(
"Max retries exceeded",
extra={"stats": retry_state.retry_object.statistics},
)
@retry(stop=stop_after_attempt(2), retry_error_callback=on_error)
def test():
raise Exception("initial exception")
Reading the source I think this callback may do what I need. Any opinions about alternatives are welcome!
def on_error(retry_state):
logging.exception(
"Max retries exceeded",
extra={"stats": retry_state.retry_object.statistics},
)
raise retry_state.retry_object.retry_error_cls(retry_state.outcome) from retry_state.outcome.exception()