How to Implement Retry Logic for Network Requests in Rust

Web
Implement retry logic in Rust by wrapping a request in a loop that catches errors and sleeps before attempting again up to a maximum limit.

Use a loop with a counter and Result propagation to retry a network request until it succeeds or the limit is reached.

use std::time::Duration;
use std::thread;

fn fetch_with_retry(url: &str, max_retries: u32) -> Result<String, String> {
    let mut attempts = 0;
    loop {
        match fetch(url) {
            Ok(data) => return Ok(data),
            Err(e) => {
                attempts += 1;
                if attempts >= max_retries {
                    return Err(e);
                }
                thread::sleep(Duration::from_secs(1));
            }
        }
    }
}

fn fetch(url: &str) -> Result<String, String> {
    // Simulated network call
    Err("Network error".to_string())
}