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