Skip to main content

maple_sdk/
error.rs

1use thiserror::Error;
2
3#[derive(Error, Debug)]
4pub enum Error {
5    #[error("HTTP request failed: {0}")]
6    Http(#[from] reqwest::Error),
7
8    #[error("Serialization error: {0}")]
9    Serialization(#[from] serde_json::Error),
10
11    #[error("CBOR error: {0}")]
12    Cbor(String),
13
14    #[error("Cryptographic error: {0}")]
15    Crypto(String),
16
17    #[error("Attestation verification failed: {0}")]
18    AttestationVerificationFailed(String),
19
20    #[error("Session error: {0}")]
21    Session(String),
22
23    #[error("Encryption error: {0}")]
24    Encryption(String),
25
26    #[error("Decryption error: {0}")]
27    Decryption(String),
28
29    #[error("Authentication error: {0}")]
30    Authentication(String),
31
32    #[error("Invalid response: {0}")]
33    InvalidResponse(String),
34
35    #[error("API error: {status}: {message}")]
36    Api { status: u16, message: String },
37
38    #[error("Configuration error: {0}")]
39    Configuration(String),
40
41    #[error("IO error: {0}")]
42    Io(#[from] std::io::Error),
43
44    #[error("UTF-8 conversion error: {0}")]
45    Utf8(#[from] std::string::FromUtf8Error),
46
47    #[error("Base64 decode error: {0}")]
48    Base64Decode(#[from] base64::DecodeError),
49
50    #[error("Other error: {0}")]
51    Other(String),
52}
53
54impl Error {
55    /// The HTTP status of an [`Error::Api`].
56    pub fn api_status(&self) -> Option<u16> {
57        match self {
58            Self::Api { status, .. } => Some(*status),
59            _ => None,
60        }
61    }
62
63    /// The backend's machine-readable code when an [`Error::Api`] body carries
64    /// one as `{"error":{"code":"..."}}`: `system_one_*` validation codes,
65    /// `usage_limit_reached`, `model_not_available_on_plan` and the like.
66    pub fn api_error_code(&self) -> Option<String> {
67        let Self::Api { message, .. } = self else {
68            return None;
69        };
70        let body: serde_json::Value = serde_json::from_str(message).ok()?;
71        body.get("error")?.get("code")?.as_str().map(str::to_owned)
72    }
73}
74
75pub type Result<T> = std::result::Result<T, Error>;
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn api_error_code_reads_the_backend_error_object() {
83        let error = Error::Api {
84            status: 422,
85            message: r#"{"status":422,"message":"At most 64 questions","error":{"message":"At most 64 questions","code":"system_one_too_many_questions"}}"#.to_string(),
86        };
87        assert_eq!(error.api_status(), Some(422));
88        assert_eq!(
89            error.api_error_code().as_deref(),
90            Some("system_one_too_many_questions")
91        );
92
93        let legacy = Error::Api {
94            status: 400,
95            message: r#"{"status":400,"message":"Bad Request"}"#.to_string(),
96        };
97        assert_eq!(legacy.api_status(), Some(400));
98        assert_eq!(legacy.api_error_code(), None);
99
100        assert_eq!(Error::Other("x".to_string()).api_status(), None);
101    }
102}