How to retry a function if the exception is NOT of a certain type using Python's tenacity?
retry_if_exception_type
will retry if there is risen an exception of a certain type. not
does not seems to work placed before the method nor before its arguments.
retry_unless_exception_type
, on the other side, loops forever, even if there is not risen error, until there is risen error of a certain type.
using retry_unless_exception_type()
combined with stop_after_attempt()
worked for me to accomplish this. the stop_after_attempt()
prevents the infinite looping.
I had to create my own class for that:
class retry_if_exception_unless_type(retry_unless_exception_type):
"""Retries until successful outcome or until an exception is raised of one or more types."""
def __call__(self, retry_state):
# don't retry if no exception was raised
if not retry_state.outcome.failed:
return False
return self.predicate(retry_state.outcome.exception())
Breaking it down a bit, what you want is to retry if:
So write that:
retry_if_exception_type() & retry_unless_exception_type(ErrorClassToNotRetryOn)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.