Skip to main content

cortexai_llm_client/
error.rs

1//! Error types for the LLM client.
2
3use thiserror::Error;
4
5/// Result type for LLM client operations.
6pub type Result<T> = std::result::Result<T, LlmClientError>;
7
8/// Errors that can occur in the LLM client.
9#[derive(Debug, Error)]
10pub enum LlmClientError {
11    /// JSON serialization error
12    #[error("Serialization error: {0}")]
13    Serialization(#[from] serde_json::Error),
14
15    /// Missing required field
16    #[error("Missing required field: {0}")]
17    MissingField(String),
18
19    /// Invalid provider
20    #[error("Unknown provider: {0}")]
21    UnknownProvider(String),
22
23    /// API error response
24    #[error("API error: {message} (type: {error_type})")]
25    ApiError {
26        error_type: String,
27        message: String,
28        code: Option<String>,
29    },
30
31    /// Unexpected response format
32    #[error("Unexpected response format: {0}")]
33    UnexpectedFormat(String),
34
35    /// Rate limit exceeded
36    #[error("Rate limit exceeded")]
37    RateLimited,
38
39    /// Authentication error
40    #[error("Authentication failed: {0}")]
41    AuthError(String),
42}
43
44impl LlmClientError {
45    /// Create a missing field error.
46    pub fn missing(field: &str) -> Self {
47        Self::MissingField(field.to_string())
48    }
49
50    /// Create an API error from response JSON.
51    pub fn from_api_response(json: &serde_json::Value) -> Self {
52        let error = &json["error"];
53        Self::ApiError {
54            error_type: error["type"].as_str().unwrap_or("unknown").to_string(),
55            message: error["message"]
56                .as_str()
57                .unwrap_or("Unknown error")
58                .to_string(),
59            code: error["code"].as_str().map(String::from),
60        }
61    }
62}