genai_types/
errors.rs

1use std::error::Error;
2use std::fmt;
3
4/// Error type for Anthropic API operations
5#[derive(Debug)]
6pub enum GenAiError {
7    /// HTTP request failed
8    HttpError(String),
9
10    /// Failed to serialize/deserialize JSON
11    JsonError(String),
12
13    /// API returned an error
14    ApiError { status: u16, message: String },
15
16    /// Unexpected response format
17    InvalidResponse(String),
18
19    /// Rate limit exceeded
20    RateLimitExceeded { retry_after: Option<u64> },
21
22    /// Authentication error
23    AuthenticationError(String),
24}
25
26impl fmt::Display for GenAiError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            GenAiError::HttpError(msg) => write!(f, "HTTP error: {}", msg),
30            GenAiError::JsonError(msg) => write!(f, "JSON error: {}", msg),
31            GenAiError::ApiError { status, message } => {
32                write!(f, "API error ({}): {}", status, message)
33            }
34            GenAiError::InvalidResponse(msg) => write!(f, "Invalid response: {}", msg),
35            GenAiError::RateLimitExceeded { retry_after } => {
36                if let Some(seconds) = retry_after {
37                    write!(f, "Rate limit exceeded. Retry after {} seconds", seconds)
38                } else {
39                    write!(f, "Rate limit exceeded")
40                }
41            }
42            GenAiError::AuthenticationError(msg) => write!(f, "Authentication error: {}", msg),
43        }
44    }
45}
46
47impl Error for GenAiError {}
48
49impl From<serde_json::Error> for GenAiError {
50    fn from(error: serde_json::Error) -> Self {
51        GenAiError::JsonError(error.to_string())
52    }
53}