Skip to main content

gitfox_client/
error.rs

1//! Typed errors for the GitFox API client.
2//!
3//! The CLI maps these onto its own stable, machine readable error codes, so
4//! variants here describe *what went wrong at the API layer* and nothing about
5//! presentation or process exit codes.
6
7use serde_json::Value;
8
9pub type Result<T> = std::result::Result<T, Error>;
10
11#[derive(Debug, thiserror::Error)]
12pub enum Error {
13    /// No credentials were supplied for a request that needs them.
14    #[error("GitFox authentication is required")]
15    AuthRequired,
16
17    /// Credentials were supplied but rejected (401/403).
18    #[error("GitFox authentication failed")]
19    AuthFailed,
20
21    /// The server answered 404 for the requested resource.
22    #[error("{kind} not found: {reference}")]
23    NotFound {
24        kind: &'static str,
25        reference: String,
26    },
27
28    /// The request did not complete within the configured timeout.
29    #[error("request timed out after {0}s")]
30    Timeout(u64),
31
32    /// DNS, TLS or connection level failure.
33    #[error("network error: {0}")]
34    Network(String),
35
36    /// The server asked us to slow down (429), optionally saying for how long.
37    #[error("rate limited by the server: {message}")]
38    RateLimited {
39        retry_after: Option<u64>,
40        message: String,
41    },
42
43    /// Any other non-success HTTP status.
44    #[error("API error (HTTP {status}): {message}")]
45    Api {
46        status: u16,
47        message: String,
48        body: Option<Value>,
49    },
50
51    /// The configured host could not be turned into a usable base URL.
52    #[error("invalid GitFox host URL: {0}")]
53    InvalidUrl(String),
54
55    /// The response body was not the JSON we expected.
56    #[error("could not decode response: {0}")]
57    Decode(String),
58
59    /// The client itself could not be constructed.
60    #[error("could not build HTTP client: {0}")]
61    Builder(String),
62}
63
64impl Error {
65    /// Best-effort extraction of a human message from a GitFox error body.
66    pub(crate) fn message_from_body(body: &Option<Value>, fallback: &str) -> String {
67        let Some(value) = body else {
68            return fallback.to_string();
69        };
70        for key in ["message", "error", "detail"] {
71            if let Some(s) = value.get(key).and_then(Value::as_str)
72                && !s.is_empty()
73            {
74                return s.to_string();
75            }
76        }
77        fallback.to_string()
78    }
79}