llm_kit_huggingface/
error.rs

1use serde::Deserialize;
2
3/// Error data from the Hugging Face API.
4#[derive(Debug, Deserialize, Clone)]
5pub struct HuggingFaceErrorData {
6    /// Error details.
7    pub error: HuggingFaceErrorDetail,
8}
9
10/// Details of an error from the Hugging Face API.
11#[derive(Debug, Deserialize, Clone)]
12pub struct HuggingFaceErrorDetail {
13    /// Error message.
14    pub message: String,
15
16    /// Error type (optional).
17    #[serde(rename = "type")]
18    pub error_type: Option<String>,
19
20    /// Error code (optional).
21    pub code: Option<String>,
22}
23
24impl HuggingFaceErrorData {
25    /// Returns the error message.
26    pub fn message(&self) -> &str {
27        &self.error.message
28    }
29
30    /// Returns the error type if available.
31    pub fn error_type(&self) -> Option<&str> {
32        self.error.error_type.as_deref()
33    }
34
35    /// Returns the error code if available.
36    pub fn code(&self) -> Option<&str> {
37        self.error.code.as_deref()
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_error_deserialization() {
47        let json = r#"{
48            "error": {
49                "message": "Invalid API key",
50                "type": "authentication_error",
51                "code": "invalid_key"
52            }
53        }"#;
54
55        let error: HuggingFaceErrorData = serde_json::from_str(json).unwrap();
56        assert_eq!(error.message(), "Invalid API key");
57        assert_eq!(error.error_type(), Some("authentication_error"));
58        assert_eq!(error.code(), Some("invalid_key"));
59    }
60
61    #[test]
62    fn test_error_deserialization_minimal() {
63        let json = r#"{
64            "error": {
65                "message": "Something went wrong"
66            }
67        }"#;
68
69        let error: HuggingFaceErrorData = serde_json::from_str(json).unwrap();
70        assert_eq!(error.message(), "Something went wrong");
71        assert_eq!(error.error_type(), None);
72        assert_eq!(error.code(), None);
73    }
74}