Skip to main content

retry/
error.rs

1use std::fmt::{self, Display, Formatter};
2
3/// Error returned when all retry attempts are exhausted.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Error<E> {
6    /// The last error that occurred.
7    pub error: E,
8    /// Total number of attempts made (at least 1).
9    pub attempts: usize,
10}
11
12impl<E> Error<E> {
13    /// Creates a new error with the last error and attempt count.
14    pub const fn new(error: E, attempts: usize) -> Self {
15        Self {
16            error,
17            attempts,
18        }
19    }
20
21    /// Consumes the error and returns the inner error.
22    pub fn into_inner(self) -> E {
23        self.error
24    }
25
26    /// Returns a reference to the inner error.
27    pub const fn inner(&self) -> &E {
28        &self.error
29    }
30
31    /// Returns the number of attempts made.
32    pub const fn attempts(&self) -> usize {
33        self.attempts
34    }
35}
36
37impl<E: Display> Display for Error<E> {
38    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
39        write!(f, "retry failed after {} attempts: {}", self.attempts, self.error)
40    }
41}
42
43impl<E: Display + std::fmt::Debug> std::error::Error for Error<E> {}