Skip to main content

retry_if

Function retry_if 

Source
pub async fn retry_if<F, Fut, T, E, P>(
    policy: &RetryPolicy,
    f: F,
    should_retry: P,
) -> Result<T, E>
where F: FnMut() -> Fut, Fut: Future<Output = Result<T, E>>, P: FnMut(&E) -> bool, E: Display,
Expand description

Retry a fallible async closure only when a predicate approves the error.

Unlike RetryPolicy::retry, errors for which should_retry returns false are propagated immediately without consuming further attempts. This is useful for distinguishing transient errors (e.g. network timeout) from permanent ones (e.g. invalid request body).

§Arguments

  • policy — The RetryPolicy controlling attempt counts and delays.
  • f — The fallible async closure to invoke.
  • should_retry — A predicate called on each error; return true to retry or false to propagate immediately.

§Returns

Ok(value) on success, or Err(error) when the predicate returns false or max_attempts are exhausted.

§Examples

use std::time::Duration;
use tokio_prompt_orchestrator::enhanced::{RetryPolicy, retry_if};

let policy = RetryPolicy::fixed(5, Duration::from_millis(10));
let result: Result<(), &str> = retry_if(
    &policy,
    || async { Err("permanent") },
    |e| *e == "transient",
).await;
assert_eq!(result.unwrap_err(), "permanent"); // stopped immediately