Skip to main content

rightkit_http/
error.rs

1use std::fmt;
2use std::time::Duration;
3
4/// Maximum error-body bytes retained on a [`HttpError::Status`].
5pub const MAX_ERROR_BODY_BYTES: usize = 64 * 1024;
6
7#[derive(Debug)]
8pub enum HttpError {
9    /// URL, header, or request construction failed before anything was sent.
10    InvalidRequest(String),
11    /// Connection, TLS, socket failure, or exhausted redirect limit.
12    /// `connect_phase` is true when nothing
13    /// can have reached the server (safe to retry any method).
14    Transport {
15        message: String,
16        connect_phase: bool,
17    },
18    /// A configured timeout elapsed.
19    Timeout(String),
20    /// Non-2xx response (after retries were exhausted or not applicable).
21    Status {
22        status: u16,
23        body: String,
24        retry_after: Option<Duration>,
25        attempts: u32,
26    },
27    /// Response body exceeded the configured limit.
28    BodyTooLarge { limit: usize },
29    /// Response was not valid JSON for the requested type.
30    Json(String),
31    /// Streaming protocol violation (oversized SSE line, bad UTF-8, ...).
32    Stream(String),
33}
34
35impl HttpError {
36    pub fn status(&self) -> Option<u16> {
37        match self {
38            HttpError::Status { status, .. } => Some(*status),
39            _ => None,
40        }
41    }
42}
43
44impl fmt::Display for HttpError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            HttpError::InvalidRequest(m) => write!(f, "invalid request: {m}"),
48            HttpError::Transport { message, .. } => write!(f, "transport error: {message}"),
49            HttpError::Timeout(m) => write!(f, "timeout: {m}"),
50            HttpError::Status {
51                status, attempts, ..
52            } => {
53                write!(f, "HTTP {status} after {attempts} attempt(s)")
54            }
55            HttpError::BodyTooLarge { limit } => write!(f, "response body exceeds {limit} bytes"),
56            HttpError::Json(m) => write!(f, "invalid JSON: {m}"),
57            HttpError::Stream(m) => write!(f, "stream error: {m}"),
58        }
59    }
60}
61
62impl std::error::Error for HttpError {}