Make a retry decision from explicit exception classes
Also published in our primary archive.
Make a retry decision from explicit exception classes
To make a retry decision from explicit exception classes, classify the caught exception with isinstance against the transient types your operation defines. Do not infer retryability from message text: messages are for people, can change, and can be identical across unrelated failures.
The deliberately broken function below retries any exception whose text contains "temporary". That makes ValueError("temporary format problem") retryable even though the fixture labels it as a permanent validation failure. The corrected should_retry function names TimeoutError as its allowed transient class. The same message is deliberately used for TimeoutError, ValueError, and PermissionError, demonstrating that only the class—not wording—controls the decision. The assertion checks all three exact outcomes.
This small classifier is policy, not a universal network rule. Some applications may also retry a particular ConnectionError, use a deadline, or inspect a structured error code. Add those cases deliberately and keep permanent errors outside the retry set. In a real retry loop, also bound attempts and account for idempotency; a True result alone does not prove that repeating an operation is safe.
TimeoutError, ValueError, and PermissionError are built-in exception classes in Python 3. See the built-in exceptions documentation.
AI assistance disclosure: This article was drafted with AI assistance and checked using the synthetic example shown below.
def retry_by_message(exc):
return "temporary" in str(exc)
def should_retry(exc):
return isinstance(exc, TimeoutError)
fixtures = [
TimeoutError("temporary problem"),
ValueError("temporary problem"),
PermissionError("temporary problem"),
]
for exc in fixtures:
print(
f"{type(exc).__name__}:"
f"message={retry_by_message(exc)}:"
f"class={should_retry(exc)}"
)
outcomes = [should_retry(exc) for exc in fixtures]
assert outcomes == [True, False, False]
TimeoutError:message=True:class=True
ValueError:message=True:class=False
PermissionError:message=True:class=False