Skip to main content

quicknode_sdk/
errors.rs

1#[derive(Debug, thiserror::Error)]
2pub enum SdkError {
3    #[error("HTTP error: {0}")]
4    Http(#[from] reqwest::Error),
5
6    #[error("API error (status {status}): {body}")]
7    Api {
8        status: reqwest::StatusCode,
9        body: String,
10    },
11
12    #[error("Failed to decode response: {source}\nBody: {body}")]
13    Decode {
14        #[source]
15        source: serde_json::Error,
16        body: String,
17    },
18
19    #[error("Invalid URL: {0}")]
20    UrlParse(#[from] url::ParseError),
21
22    #[error("Configuration error: {0}")]
23    Config(String),
24}
25
26// Classifies a transport-level HTTP failure. Bindings use this to pick a
27// typed exception subclass (TimeoutError / ConnectionError / HttpError) so the
28// reqwest predicate logic lives in one place.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum HttpKind {
31    Timeout,
32    Connect,
33    Other,
34}
35
36impl SdkError {
37    pub fn http_kind(&self) -> Option<HttpKind> {
38        match self {
39            SdkError::Http(e) if e.is_timeout() => Some(HttpKind::Timeout),
40            SdkError::Http(e) if e.is_connect() => Some(HttpKind::Connect),
41            SdkError::Http(_) => Some(HttpKind::Other),
42            _ => None,
43        }
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn api_error_display_includes_status_and_body() {
53        let err = SdkError::Api {
54            status: reqwest::StatusCode::NOT_FOUND,
55            body: "not found".to_string(),
56        };
57        let s = err.to_string();
58        assert!(s.contains("404"), "expected 404 in {s}");
59        assert!(s.contains("not found"), "expected body in {s}");
60    }
61
62    #[test]
63    fn config_error_display() {
64        let err = SdkError::Config("missing api key".to_string());
65        assert!(err.to_string().contains("missing api key"));
66    }
67
68    #[test]
69    #[allow(clippy::unwrap_used)]
70    fn http_kind_none_for_non_http_variants() {
71        assert!(SdkError::Config("x".to_string()).http_kind().is_none());
72        let decode_err = SdkError::Decode {
73            source: serde_json::from_str::<i32>("bad").unwrap_err(),
74            body: "bad".to_string(),
75        };
76        assert!(decode_err.http_kind().is_none());
77    }
78}