Skip to main content

toolkit_http/
error.rs

1use std::time::Duration;
2use thiserror::Error;
3
4/// Classification of URL validation failures.
5///
6/// Provides programmatic matching for different failure modes without
7/// relying on unstable error message strings.
8///
9/// # Example
10///
11/// ```ignore
12/// match &err {
13///     HttpError::InvalidUri { kind, .. } => match kind {
14///         InvalidUriKind::ParseError => println!("Malformed URL syntax"),
15///         InvalidUriKind::MissingAuthority => println!("URL needs a host"),
16///         InvalidUriKind::MissingScheme => println!("URL needs http:// or https://"),
17///         _ => println!("Other URI error"),
18///     },
19///     _ => {}
20/// }
21/// ```
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum InvalidUriKind {
25    /// URL could not be parsed (malformed syntax)
26    ParseError,
27    /// URL is missing required host/authority component
28    MissingAuthority,
29    /// URL is missing required scheme (http/https)
30    MissingScheme,
31}
32
33/// HTTP client error types
34#[derive(Error, Debug)]
35#[non_exhaustive]
36pub enum HttpError {
37    /// Request building failed
38    #[error("Failed to build request: {0}")]
39    RequestBuild(#[from] http::Error),
40
41    /// Invalid header name
42    #[error("Invalid header name: {0}")]
43    InvalidHeaderName(#[from] http::header::InvalidHeaderName),
44
45    /// Invalid header value
46    #[error("Invalid header value: {0}")]
47    InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
48
49    /// Single request attempt timed out
50    #[error("Request attempt timed out after {0:?}")]
51    Timeout(std::time::Duration),
52
53    /// Total operation deadline exceeded (including all retries)
54    #[error("Operation deadline exceeded after {0:?}")]
55    DeadlineExceeded(std::time::Duration),
56
57    /// Transport error (network, connection, etc)
58    #[error("Transport error: {0}")]
59    Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
60
61    /// TLS error
62    #[error("TLS error: {0}")]
63    Tls(#[source] Box<dyn std::error::Error + Send + Sync>),
64
65    /// Response body exceeded size limit
66    #[error("Response body too large: limit {limit} bytes, got {actual} bytes")]
67    BodyTooLarge { limit: usize, actual: usize },
68
69    /// HTTP non-2xx status
70    #[error("HTTP {status}: {body_preview}")]
71    HttpStatus {
72        status: http::StatusCode,
73        body_preview: String,
74        content_type: Option<String>,
75        /// Parsed `Retry-After` header value, if present and valid
76        retry_after: Option<Duration>,
77    },
78
79    /// JSON parsing error
80    #[error("JSON parsing failed: {0}")]
81    Json(#[from] serde_json::Error),
82
83    /// Form URL encoding error
84    #[error("Form encoding failed: {0}")]
85    FormEncode(#[from] serde_urlencoded::ser::Error),
86
87    /// Service overloaded (concurrency limit reached, fail-fast)
88    #[error("Service overloaded: concurrency limit reached")]
89    Overloaded,
90
91    /// Internal service failure (buffer worker died, channel closed)
92    #[error("Service unavailable: internal failure")]
93    ServiceClosed,
94
95    /// Invalid URL (failed to parse)
96    ///
97    /// Use the `kind` field for programmatic matching. The `reason` field contains
98    /// a diagnostic message intended for logging only; do not match on its contents
99    /// as the format is unstable and may change between releases.
100    #[error("Invalid URL '{url}': {reason}")]
101    InvalidUri {
102        /// The URL that failed to parse
103        url: String,
104        /// Structured failure classification for programmatic matching
105        kind: InvalidUriKind,
106        /// Diagnostic message (unstable format, for logging only)
107        reason: String,
108    },
109
110    /// Invalid URL scheme for transport security configuration
111    #[error("URL scheme '{scheme}' not allowed: {reason}")]
112    InvalidScheme {
113        /// The URL scheme that was rejected
114        scheme: String,
115        /// Reason the scheme was rejected
116        reason: String,
117    },
118
119    /// The outbound proxy is misconfigured or refused the `CONNECT` tunnel.
120    /// Replies of a proxy to plain HTTP requests are ordinary responses.
121    ///
122    /// [`ProxyErrorKind::InvalidUrl`], [`UnsupportedScheme`] and
123    /// [`AuthRequired`] are not retried: retrying a bad proxy URL or rejected
124    /// credentials repeats the same failure (and can lock the proxy account).
125    /// [`TunnelRejected`] is retried like a transport error.
126    ///
127    /// [`UnsupportedScheme`]: ProxyErrorKind::UnsupportedScheme
128    /// [`AuthRequired`]: ProxyErrorKind::AuthRequired
129    /// [`TunnelRejected`]: ProxyErrorKind::TunnelRejected
130    #[error("proxy '{proxy}': {kind}")]
131    #[non_exhaustive]
132    Proxy {
133        /// What went wrong.
134        kind: ProxyErrorKind,
135        /// Proxy URL with credentials removed.
136        proxy: String,
137    },
138}
139
140/// Classification of [`HttpError::Proxy`].
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum ProxyErrorKind {
144    /// Not a usable URL: unencoded `@`, `/`, `?` or `#` in the credentials,
145    /// an empty host or a port out of range.
146    InvalidUrl,
147    /// A scheme other than `http` or `https`, e.g. SOCKS.
148    UnsupportedScheme,
149    /// The proxy answered `CONNECT` with `407 Proxy Authentication Required`.
150    AuthRequired,
151    /// The proxy answered `CONNECT` with another non-success status (e.g. 403,
152    /// 502, 503) or with a reply that is not valid HTTP. Retried, since a 5xx
153    /// from a proxy is often temporary; hyper-util does not expose the status.
154    TunnelRejected,
155}
156
157impl std::fmt::Display for ProxyErrorKind {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        f.write_str(match self {
160            Self::InvalidUrl => {
161                "invalid proxy URL (check host and port; percent-encode reserved characters in credentials)"
162            }
163            Self::UnsupportedScheme => {
164                "unsupported proxy scheme, only http:// and https:// are supported"
165            }
166            Self::AuthRequired => "proxy authentication required (407)",
167            Self::TunnelRejected => "proxy rejected the CONNECT request",
168        })
169    }
170}
171
172impl From<hyper::Error> for HttpError {
173    fn from(err: hyper::Error) -> Self {
174        HttpError::Transport(Box::new(err))
175    }
176}
177
178impl From<hyper_util::client::legacy::Error> for HttpError {
179    fn from(err: hyper_util::client::legacy::Error) -> Self {
180        HttpError::Transport(Box::new(err))
181    }
182}
183
184#[cfg(test)]
185#[cfg_attr(coverage_nightly, coverage(off))]
186mod tests {
187    use super::*;
188    use std::error::Error;
189    use std::fmt;
190
191    #[derive(Debug)]
192    struct TestError(&'static str);
193
194    impl fmt::Display for TestError {
195        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196            write!(f, "{}", self.0)
197        }
198    }
199
200    impl Error for TestError {}
201
202    #[test]
203    fn test_transport_error_preserves_source() {
204        let inner = TestError("connection refused");
205        let err = HttpError::Transport(Box::new(inner));
206
207        // Verify source() returns the inner error
208        let source = err.source();
209        assert!(source.is_some(), "Transport error should have a source");
210
211        // Verify we can downcast to the original error type
212        let source = source.unwrap();
213        let downcast = source.downcast_ref::<TestError>();
214        assert!(
215            downcast.is_some(),
216            "Should be able to downcast to TestError"
217        );
218        assert_eq!(downcast.unwrap().0, "connection refused");
219    }
220
221    #[test]
222    fn test_tls_error_preserves_source() {
223        let inner = TestError("certificate expired");
224        let err = HttpError::Tls(Box::new(inner));
225
226        let source = err.source();
227        assert!(source.is_some(), "TLS error should have a source");
228
229        let source = source.unwrap();
230        let downcast = source.downcast_ref::<TestError>();
231        assert!(downcast.is_some());
232        assert_eq!(downcast.unwrap().0, "certificate expired");
233    }
234
235    #[test]
236    fn test_error_chain_traversal() {
237        let inner = TestError("root cause");
238        let err = HttpError::Transport(Box::new(inner));
239
240        // Count errors in chain
241        let mut count = 0;
242        let mut current: Option<&(dyn Error + 'static)> = Some(&err);
243        while let Some(e) = current {
244            count += 1;
245            current = e.source();
246        }
247
248        assert_eq!(
249            count, 2,
250            "Should have 2 errors in chain: HttpError and TestError"
251        );
252    }
253}