Skip to main content

adk_model/anthropic/
error.rs

1//! Structured error types for the Anthropic provider.
2//!
3//! Provides [`AnthropicApiError`] for API-level errors with full diagnostic
4//! context (error type, message, status code, request ID) and
5//! [`ConversionError`] for content mapping failures.
6
7use adk_core::AdkError;
8
9/// Structured Anthropic API error preserving all diagnostic context.
10///
11/// Captures the error type, message, HTTP status code, and optional request ID
12/// returned by the Anthropic API, enabling precise debugging and support
13/// escalation.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_model::anthropic::AnthropicApiError;
19///
20/// let err = AnthropicApiError {
21///     error_type: "rate_limit_error".to_string(),
22///     message: "Too many requests".to_string(),
23///     status_code: 429,
24///     request_id: Some("req_abc123".to_string()),
25/// };
26///
27/// assert!(err.to_string().contains("429"));
28/// assert!(err.to_string().contains("rate_limit_error"));
29/// assert!(err.to_string().contains("req_abc123"));
30/// ```
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct AnthropicApiError {
33    /// Error type from Anthropic (e.g., "invalid_request_error", "rate_limit_error").
34    pub error_type: String,
35    /// Human-readable error message.
36    pub message: String,
37    /// HTTP status code.
38    pub status_code: u16,
39    /// Request ID from the `request-id` response header.
40    pub request_id: Option<String>,
41}
42
43impl std::fmt::Display for AnthropicApiError {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(
46            f,
47            "Anthropic API error ({}): {} [type={}]",
48            self.status_code, self.message, self.error_type
49        )?;
50        if let Some(ref rid) = self.request_id {
51            write!(f, " [request_id={rid}]")?;
52        }
53        Ok(())
54    }
55}
56
57impl std::error::Error for AnthropicApiError {}
58
59impl From<AnthropicApiError> for AdkError {
60    /// The message quotes at most [`adk_core::UPSTREAM_EXCERPT_BYTES`] of the API's message,
61    /// which can echo the request.
62    fn from(err: AnthropicApiError) -> Self {
63        use adk_core::ErrorComponent;
64        let msg = AnthropicApiError {
65            message: adk_core::upstream_excerpt(&err.message).to_string(),
66            ..err.clone()
67        }
68        .to_string();
69        // Anthropic documents `api_error` (500) and `overloaded_error` (529) as transient.
70        let category = crate::retry::category_for_status_code(err.status_code);
71        let mut adk_err =
72            AdkError::new(ErrorComponent::Model, category, "model.anthropic.api_error", msg)
73                .with_upstream_status(err.status_code)
74                .with_provider("anthropic");
75        if let Some(ref rid) = err.request_id {
76            adk_err = adk_err.with_request_id(rid.clone());
77        }
78        let adk_err = crate::error_metadata::classify_quota(
79            adk_err,
80            crate::error_metadata::is_quota_exhausted(&err.error_type),
81        );
82        crate::error_metadata::with_code(adk_err, Some(&err.error_type))
83    }
84}
85
86/// Error type for content conversion failures.
87///
88/// Used when mapping ADK content types to Anthropic API types encounters
89/// unsupported or invalid content.
90///
91/// # Example
92///
93/// ```rust
94/// use adk_model::anthropic::ConversionError;
95///
96/// let err = ConversionError::UnsupportedMimeType("audio/wav".to_string());
97/// assert!(err.to_string().contains("audio/wav"));
98/// ```
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum ConversionError {
101    /// The MIME type is not supported by the Anthropic API.
102    UnsupportedMimeType(String),
103    /// A provider-native tool declaration could not be deserialized.
104    InvalidToolDeclaration(String),
105}
106
107impl std::fmt::Display for ConversionError {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        match self {
110            ConversionError::UnsupportedMimeType(mime) => {
111                write!(f, "unsupported MIME type for Anthropic API: {mime}")
112            }
113            ConversionError::InvalidToolDeclaration(message) => write!(f, "{message}"),
114        }
115    }
116}
117
118impl std::error::Error for ConversionError {}
119
120impl From<ConversionError> for AdkError {
121    fn from(err: ConversionError) -> Self {
122        AdkError::model(err.to_string())
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn test_api_error_display_with_request_id() {
132        let err = AnthropicApiError {
133            error_type: "rate_limit_error".to_string(),
134            message: "Too many requests".to_string(),
135            status_code: 429,
136            request_id: Some("req_abc123".to_string()),
137        };
138        let display = err.to_string();
139        assert!(display.contains("429"));
140        assert!(display.contains("rate_limit_error"));
141        assert!(display.contains("Too many requests"));
142        assert!(display.contains("req_abc123"));
143    }
144
145    #[test]
146    fn test_api_error_display_without_request_id() {
147        let err = AnthropicApiError {
148            error_type: "invalid_request_error".to_string(),
149            message: "Invalid model".to_string(),
150            status_code: 400,
151            request_id: None,
152        };
153        let display = err.to_string();
154        assert!(display.contains("400"));
155        assert!(display.contains("invalid_request_error"));
156        assert!(display.contains("Invalid model"));
157        assert!(!display.contains("request_id"));
158    }
159
160    #[test]
161    fn test_api_error_into_adk_error() {
162        let err = AnthropicApiError {
163            error_type: "overloaded_error".to_string(),
164            message: "Server overloaded".to_string(),
165            status_code: 529,
166            request_id: Some("req_xyz".to_string()),
167        };
168        let adk_err: AdkError = err.into();
169        assert!(adk_err.is_model());
170        assert!(adk_err.to_string().contains("529"));
171        assert_eq!(adk_err.details.upstream_status_code, Some(529));
172        assert_eq!(adk_err.details.provider.as_deref(), Some("anthropic"));
173        assert_eq!(
174            adk_err.details.metadata.get("provider_error_code").and_then(serde_json::Value::as_str),
175            Some("overloaded_error")
176        );
177        assert!(adk_err.is_retryable(), "529 should be retryable (Unavailable category)");
178    }
179
180    #[test]
181    fn excludes_invalid_provider_codes() {
182        let oversized = "x".repeat(129);
183        for error_type in ["", "bad code", "line\nbreak", oversized.as_str()] {
184            let error = AnthropicApiError {
185                error_type: error_type.to_string(),
186                message: "Bad request".to_string(),
187                status_code: 400,
188                request_id: Some("req_123".to_string()),
189            };
190            let display = error.to_string();
191            let mapped: AdkError = error.into();
192            assert_eq!(mapped.category, adk_core::ErrorCategory::InvalidInput);
193            assert_eq!(mapped.code, "model.anthropic.api_error");
194            assert_eq!(mapped.message, display);
195            assert_eq!(mapped.details.upstream_status_code, Some(400));
196            assert_eq!(mapped.details.request_id.as_deref(), Some("req_123"));
197            assert!(!mapped.is_retryable());
198            assert!(!mapped.details.metadata.contains_key("provider_error_code"));
199        }
200    }
201
202    #[test]
203    fn transient_server_errors_are_retryable() {
204        for (error_type, status_code) in [
205            ("api_error", 500),
206            ("api_error", 502),
207            ("timeout_error", 504),
208            ("overloaded_error", 529),
209        ] {
210            let adk_err: AdkError = AnthropicApiError {
211                error_type: error_type.to_string(),
212                message: "transient".to_string(),
213                status_code,
214                request_id: None,
215            }
216            .into();
217            assert_eq!(adk_err.category, adk_core::ErrorCategory::Unavailable, "{status_code}");
218            assert!(adk_err.is_retryable(), "{status_code} should be retryable");
219            assert_eq!(adk_err.details.upstream_status_code, Some(status_code));
220        }
221
222        let client_error: AdkError = AnthropicApiError {
223            error_type: "client_error".to_string(),
224            message: "bad".to_string(),
225            status_code: 0,
226            request_id: None,
227        }
228        .into();
229        assert!(!client_error.is_retryable());
230    }
231
232    #[test]
233    fn a_billing_error_is_not_retried() {
234        let adk_err: AdkError = AnthropicApiError {
235            error_type: "billing_error".to_string(),
236            message: "Your credit balance is too low to access the Anthropic API.".to_string(),
237            status_code: 402,
238            request_id: None,
239        }
240        .into();
241        assert_eq!(adk_err.category, adk_core::ErrorCategory::ResourceExhausted);
242        assert!(!adk_err.is_retryable());
243        assert!(adk_err.message.contains("add credit or raise the limit"), "{}", adk_err.message);
244        assert_eq!(adk_err.details.metadata["provider_error_code"], "billing_error");
245    }
246
247    #[test]
248    fn test_conversion_error_display() {
249        let err = ConversionError::UnsupportedMimeType("audio/wav".to_string());
250        assert!(err.to_string().contains("audio/wav"));
251        assert!(err.to_string().contains("unsupported MIME type"));
252    }
253
254    #[test]
255    fn test_conversion_error_into_adk_error() {
256        let err = ConversionError::UnsupportedMimeType("video/mp4".to_string());
257        let adk_err: AdkError = err.into();
258        assert!(adk_err.is_model());
259        assert!(adk_err.to_string().contains("video/mp4"));
260    }
261}