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