Skip to main content

tower_timelimiter/
error.rs

1//! Error types for time limiter.
2
3use std::fmt;
4
5/// Errors that can occur in the time limiter.
6#[derive(Debug)]
7pub enum TimeLimiterError<E> {
8    /// The request timed out.
9    Timeout,
10    /// The inner service returned an error.
11    Inner(E),
12}
13
14impl<E: fmt::Display> fmt::Display for TimeLimiterError<E> {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        match self {
17            TimeLimiterError::Timeout => write!(f, "request timed out"),
18            TimeLimiterError::Inner(e) => write!(f, "inner service error: {}", e),
19        }
20    }
21}
22
23impl<E: std::error::Error + 'static> std::error::Error for TimeLimiterError<E> {
24    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
25        match self {
26            TimeLimiterError::Timeout => None,
27            TimeLimiterError::Inner(e) => Some(e),
28        }
29    }
30}
31
32impl<E> TimeLimiterError<E> {
33    /// Returns true if this is a timeout error.
34    pub fn is_timeout(&self) -> bool {
35        matches!(self, TimeLimiterError::Timeout)
36    }
37
38    /// Converts this error into the inner error, if any.
39    pub fn into_inner(self) -> Option<E> {
40        match self {
41            TimeLimiterError::Timeout => None,
42            TimeLimiterError::Inner(e) => Some(e),
43        }
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_timeout_error() {
53        let err: TimeLimiterError<&str> = TimeLimiterError::Timeout;
54        assert!(err.is_timeout());
55        assert_eq!(err.into_inner(), None);
56    }
57
58    #[test]
59    fn test_inner_error() {
60        let err = TimeLimiterError::Inner("inner error");
61        assert!(!err.is_timeout());
62        assert_eq!(err.into_inner(), Some("inner error"));
63    }
64
65    #[test]
66    fn test_error_display() {
67        let err: TimeLimiterError<&str> = TimeLimiterError::Timeout;
68        assert_eq!(err.to_string(), "request timed out");
69
70        let err = TimeLimiterError::Inner("test");
71        assert_eq!(err.to_string(), "inner service error: test");
72    }
73}