Skip to main content

adk_anthropic/
error.rs

1//! Error types for the adk-anthropic client.
2//!
3//! This module defines a comprehensive error type system for handling
4//! all possible errors that can occur when interacting with the Anthropic API.
5
6use std::error;
7use std::fmt;
8use std::io;
9use std::str::Utf8Error;
10use std::sync::Arc;
11
12/// The main error type for the adk-anthropic client.
13#[derive(Clone, Debug)]
14pub enum Error {
15    /// A generic API error occurred.
16    Api {
17        /// HTTP status code.
18        status_code: u16,
19        /// Error type string from the API.
20        error_type: Option<String>,
21        /// Human-readable error message.
22        message: String,
23        /// Request ID for debugging and support.
24        request_id: Option<String>,
25        /// Server-suggested retry delay in seconds.
26        retry_after: Option<u64>,
27    },
28
29    /// Authentication error.
30    Authentication {
31        /// Human-readable error message.
32        message: String,
33    },
34
35    /// Authorization/Permission error.
36    Permission {
37        /// Human-readable error message.
38        message: String,
39    },
40
41    /// Resource not found.
42    NotFound {
43        /// Human-readable error message.
44        message: String,
45        /// Resource type.
46        resource_type: Option<String>,
47        /// Resource ID.
48        resource_id: Option<String>,
49    },
50
51    /// Rate limit exceeded.
52    RateLimit {
53        /// Actual HTTP status, including 529 overload responses.
54        status_code: u16,
55        /// Human-readable error message.
56        message: String,
57        /// Time to wait before retrying, in seconds.
58        retry_after: Option<u64>,
59    },
60
61    /// Bad request due to invalid parameters.
62    BadRequest {
63        /// Human-readable error message.
64        message: String,
65        /// Parameter that caused the error.
66        param: Option<String>,
67    },
68
69    /// API timeout error.
70    Timeout {
71        /// HTTP status for a server timeout, absent for local transport timeouts.
72        status_code: Option<u16>,
73        /// Human-readable error message.
74        message: String,
75        /// Duration of the timeout in seconds.
76        duration: Option<f64>,
77    },
78
79    /// Request was aborted by the client.
80    Abort {
81        /// Human-readable error message.
82        message: String,
83    },
84
85    /// Connection error.
86    Connection {
87        /// Human-readable error message.
88        message: String,
89        /// Underlying cause.
90        source: Option<Arc<dyn error::Error + Send + Sync>>,
91    },
92
93    /// Server returned a 500 internal error.
94    InternalServer {
95        /// Human-readable error message.
96        message: String,
97        /// Request ID for debugging and support.
98        request_id: Option<String>,
99        /// Server-suggested retry delay in seconds.
100        retry_after: Option<u64>,
101    },
102
103    /// Server is overloaded or unavailable.
104    ServiceUnavailable {
105        /// Actual HTTP status of the unavailable response.
106        status_code: u16,
107        /// Human-readable error message.
108        message: String,
109        /// Time to wait before retrying, in seconds.
110        retry_after: Option<u64>,
111    },
112
113    /// Error during JSON serialization or deserialization.
114    Serialization {
115        /// Human-readable error message.
116        message: String,
117        /// The underlying error.
118        source: Option<Arc<dyn error::Error + Send + Sync>>,
119    },
120
121    /// I/O error.
122    Io {
123        /// Human-readable error message.
124        message: String,
125        /// The underlying error.
126        source: Arc<io::Error>,
127    },
128
129    /// HTTP client error.
130    HttpClient {
131        /// Human-readable error message.
132        message: String,
133        /// The underlying error.
134        source: Option<Arc<dyn error::Error + Send + Sync>>,
135    },
136
137    /// Error during validation of request parameters.
138    Validation {
139        /// Human-readable error message.
140        message: String,
141        /// Parameter that failed validation.
142        param: Option<String>,
143    },
144
145    /// A URL parsing or manipulation error.
146    Url {
147        /// Human-readable error message.
148        message: String,
149        /// The underlying error.
150        source: Option<url::ParseError>,
151    },
152
153    /// A streaming error occurred.
154    Streaming {
155        /// Human-readable error message.
156        message: String,
157        /// The underlying error.
158        source: Option<Arc<dyn error::Error + Send + Sync>>,
159    },
160
161    /// Encoding/decoding error.
162    Encoding {
163        /// Human-readable error message.
164        message: String,
165        /// The underlying error.
166        source: Option<Arc<dyn error::Error + Send + Sync>>,
167    },
168
169    /// Unknown error.
170    Unknown {
171        /// Human-readable error message.
172        message: String,
173    },
174
175    /// Unimplemented functionality.
176    ToDo {
177        /// Human-readable error message.
178        message: String,
179    },
180}
181
182impl Error {
183    /// Creates a new API error.
184    pub fn api(
185        status_code: u16,
186        error_type: Option<String>,
187        message: String,
188        request_id: Option<String>,
189    ) -> Self {
190        Error::Api { status_code, error_type, message, request_id, retry_after: None }
191    }
192
193    /// Creates a new authentication error.
194    pub fn authentication(message: impl Into<String>) -> Self {
195        Error::Authentication { message: message.into() }
196    }
197
198    /// Creates a new permission error.
199    pub fn permission(message: impl Into<String>) -> Self {
200        Error::Permission { message: message.into() }
201    }
202
203    /// Creates a new not found error.
204    pub fn not_found(
205        message: impl Into<String>,
206        resource_type: Option<String>,
207        resource_id: Option<String>,
208    ) -> Self {
209        Error::NotFound { message: message.into(), resource_type, resource_id }
210    }
211
212    /// Creates a new rate limit error.
213    pub fn rate_limit(message: impl Into<String>, retry_after: Option<u64>) -> Self {
214        Error::RateLimit { status_code: 429, message: message.into(), retry_after }
215    }
216
217    /// Creates a new bad request error.
218    pub fn bad_request(message: impl Into<String>, param: Option<String>) -> Self {
219        Error::BadRequest { message: message.into(), param }
220    }
221
222    /// Creates a new timeout error.
223    pub fn timeout(message: impl Into<String>, duration: Option<f64>) -> Self {
224        Error::Timeout { status_code: None, message: message.into(), duration }
225    }
226
227    /// Creates a new abort error.
228    pub fn abort(message: impl Into<String>) -> Self {
229        Error::Abort { message: message.into() }
230    }
231
232    /// Creates a new connection error.
233    pub fn connection(
234        message: impl Into<String>,
235        source: Option<Box<dyn error::Error + Send + Sync>>,
236    ) -> Self {
237        Error::Connection { message: message.into(), source: source.map(Arc::from) }
238    }
239
240    /// Creates a new internal server error.
241    pub fn internal_server(message: impl Into<String>, request_id: Option<String>) -> Self {
242        Error::InternalServer { message: message.into(), request_id, retry_after: None }
243    }
244
245    /// Creates an Anthropic overloaded-service error (HTTP 529).
246    pub fn service_unavailable(message: impl Into<String>, retry_after: Option<u64>) -> Self {
247        Error::ServiceUnavailable { status_code: 529, message: message.into(), retry_after }
248    }
249
250    /// Creates a new serialization error.
251    pub fn serialization(
252        message: impl Into<String>,
253        source: Option<Box<dyn error::Error + Send + Sync>>,
254    ) -> Self {
255        Error::Serialization { message: message.into(), source: source.map(Arc::from) }
256    }
257
258    /// Creates a new I/O error.
259    pub fn io(message: impl Into<String>, source: io::Error) -> Self {
260        Error::Io { message: message.into(), source: Arc::new(source) }
261    }
262
263    /// Creates a new HTTP client error.
264    pub fn http_client(
265        message: impl Into<String>,
266        source: Option<Box<dyn error::Error + Send + Sync>>,
267    ) -> Self {
268        Error::HttpClient { message: message.into(), source: source.map(Arc::from) }
269    }
270
271    /// Creates a new validation error.
272    pub fn validation(message: impl Into<String>, param: Option<String>) -> Self {
273        Error::Validation { message: message.into(), param }
274    }
275
276    /// Creates a new URL error.
277    pub fn url(message: impl Into<String>, source: Option<url::ParseError>) -> Self {
278        Error::Url { message: message.into(), source }
279    }
280
281    /// Creates a new streaming error.
282    pub fn streaming(
283        message: impl Into<String>,
284        source: Option<Box<dyn error::Error + Send + Sync>>,
285    ) -> Self {
286        Error::Streaming { message: message.into(), source: source.map(Arc::from) }
287    }
288
289    /// Creates a new encoding error.
290    pub fn encoding(
291        message: impl Into<String>,
292        source: Option<Box<dyn error::Error + Send + Sync>>,
293    ) -> Self {
294        Error::Encoding { message: message.into(), source: source.map(Arc::from) }
295    }
296
297    /// Creates a new unknown error.
298    pub fn unknown(message: impl Into<String>) -> Self {
299        Error::Unknown { message: message.into() }
300    }
301
302    /// Creates a new ToDo error for unimplemented functionality.
303    pub fn todo(message: impl Into<String>) -> Self {
304        Error::ToDo { message: message.into() }
305    }
306
307    /// Returns true if this error is related to authentication.
308    pub fn is_authentication(&self) -> bool {
309        matches!(self, Error::Authentication { .. })
310    }
311
312    /// Returns true if this error is related to permissions.
313    pub fn is_permission(&self) -> bool {
314        matches!(self, Error::Permission { .. })
315    }
316
317    /// Returns true if this error is a "not found" error.
318    pub fn is_not_found(&self) -> bool {
319        matches!(self, Error::NotFound { .. })
320    }
321
322    /// Returns true if this error is related to rate limiting.
323    pub fn is_rate_limit(&self) -> bool {
324        matches!(self, Error::RateLimit { .. })
325    }
326
327    /// Returns true if this error is a bad request.
328    pub fn is_bad_request(&self) -> bool {
329        matches!(self, Error::BadRequest { .. })
330    }
331
332    /// Returns true if this error is a timeout.
333    pub fn is_timeout(&self) -> bool {
334        matches!(self, Error::Timeout { .. })
335    }
336
337    /// Returns true if this error is an abort.
338    pub fn is_abort(&self) -> bool {
339        matches!(self, Error::Abort { .. })
340    }
341
342    /// Returns true if this error is a connection error.
343    pub fn is_connection(&self) -> bool {
344        matches!(self, Error::Connection { .. })
345    }
346
347    /// Returns true if this error is a server error.
348    pub fn is_server_error(&self) -> bool {
349        matches!(self, Error::InternalServer { .. } | Error::ServiceUnavailable { .. })
350    }
351
352    /// Returns true if this error is retryable.
353    pub fn is_retryable(&self) -> bool {
354        match self {
355            Error::Api { status_code, .. } => {
356                matches!(status_code, 408 | 409 | 429 | 500..=599)
357            }
358            Error::Timeout { .. } => true,
359            Error::Connection { .. } => true,
360            Error::RateLimit { .. } => true,
361            Error::ServiceUnavailable { .. } => true,
362            Error::InternalServer { .. } => true,
363            _ => false,
364        }
365    }
366
367    /// Returns true if this error is a ToDo error.
368    pub fn is_todo(&self) -> bool {
369        matches!(self, Error::ToDo { .. })
370    }
371
372    /// Returns true if this error is a validation error.
373    pub fn is_validation(&self) -> bool {
374        matches!(self, Error::Validation { .. })
375    }
376
377    /// Returns the request ID associated with this error, if any.
378    pub fn request_id(&self) -> Option<&str> {
379        match self {
380            Error::Api { request_id, .. } => request_id.as_deref(),
381            Error::InternalServer { request_id, .. } => request_id.as_deref(),
382            _ => None,
383        }
384    }
385
386    /// Returns the server-suggested retry delay in seconds.
387    ///
388    /// # Example
389    ///
390    /// ```
391    /// let error = adk_anthropic::Error::rate_limit("Busy", Some(7));
392    /// assert_eq!(error.retry_after(), Some(7));
393    /// ```
394    pub fn retry_after(&self) -> Option<u64> {
395        match self {
396            Self::Api { retry_after, .. }
397            | Self::RateLimit { retry_after, .. }
398            | Self::InternalServer { retry_after, .. }
399            | Self::ServiceUnavailable { retry_after, .. } => *retry_after,
400            _ => None,
401        }
402    }
403
404    /// Returns the status code associated with this error, if any.
405    pub fn status_code(&self) -> Option<u16> {
406        match self {
407            Error::Api { status_code, .. }
408            | Error::RateLimit { status_code, .. }
409            | Error::ServiceUnavailable { status_code, .. } => Some(*status_code),
410            Error::Timeout { status_code, .. } => *status_code,
411            Error::InternalServer { .. } => Some(500),
412            Error::Authentication { .. } => Some(401),
413            Error::Permission { .. } => Some(403),
414            Error::NotFound { .. } => Some(404),
415            Error::BadRequest { .. } => Some(400),
416            _ => None,
417        }
418    }
419}
420
421impl fmt::Display for Error {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        match self {
424            Error::Api { message, error_type, request_id, .. } => {
425                if let Some(error_type) = error_type {
426                    if let Some(request_id) = request_id {
427                        write!(f, "{error_type}: {message} (Request ID: {request_id})")
428                    } else {
429                        write!(f, "{error_type}: {message}")
430                    }
431                } else if let Some(request_id) = request_id {
432                    write!(f, "API error: {message} (Request ID: {request_id})")
433                } else {
434                    write!(f, "API error: {message}")
435                }
436            }
437            Error::Authentication { message } => {
438                write!(f, "Authentication error: {message}")
439            }
440            Error::Permission { message } => {
441                write!(f, "Permission error: {message}")
442            }
443            Error::NotFound { message, resource_type, resource_id } => {
444                let prefix = if let Some(resource_type) = resource_type {
445                    format!("Resource not found ({resource_type})")
446                } else {
447                    "Resource not found".to_string()
448                };
449
450                let suffix = if let Some(resource_id) = resource_id {
451                    format!(" [ID: {resource_id}]")
452                } else {
453                    "".to_string()
454                };
455
456                write!(f, "{prefix}: {message}{suffix}")
457            }
458            Error::RateLimit { message, retry_after, .. } => {
459                if let Some(retry_after) = retry_after {
460                    write!(f, "Rate limit exceeded: {message} (retry after {retry_after} seconds)")
461                } else {
462                    write!(f, "Rate limit exceeded: {message}")
463                }
464            }
465            Error::BadRequest { message, param } => {
466                if let Some(param) = param {
467                    write!(f, "Bad request: {message} (parameter: {param})")
468                } else {
469                    write!(f, "Bad request: {message}")
470                }
471            }
472            Error::Timeout { message, duration, .. } => {
473                if let Some(duration) = duration {
474                    write!(f, "Timeout error: {message} ({duration} seconds)")
475                } else {
476                    write!(f, "Timeout error: {message}")
477                }
478            }
479            Error::Abort { message } => {
480                write!(f, "Request aborted: {message}")
481            }
482            Error::Connection { message, .. } => {
483                write!(f, "Connection error: {message}")
484            }
485            Error::InternalServer { message, request_id, .. } => {
486                if let Some(request_id) = request_id {
487                    write!(f, "Internal server error: {message} (Request ID: {request_id})")
488                } else {
489                    write!(f, "Internal server error: {message}")
490                }
491            }
492            Error::ServiceUnavailable { message, retry_after, .. } => {
493                if let Some(retry_after) = retry_after {
494                    write!(f, "Service unavailable: {message} (retry after {retry_after} seconds)")
495                } else {
496                    write!(f, "Service unavailable: {message}")
497                }
498            }
499            Error::Serialization { message, .. } => {
500                write!(f, "Serialization error: {message}")
501            }
502            Error::Io { message, .. } => {
503                write!(f, "I/O error: {message}")
504            }
505            Error::HttpClient { message, .. } => {
506                write!(f, "HTTP client error: {message}")
507            }
508            Error::Validation { message, param } => {
509                if let Some(param) = param {
510                    write!(f, "Validation error: {message} (parameter: {param})")
511                } else {
512                    write!(f, "Validation error: {message}")
513                }
514            }
515            Error::Url { message, .. } => {
516                write!(f, "URL error: {message}")
517            }
518            Error::Streaming { message, .. } => {
519                write!(f, "Streaming error: {message}")
520            }
521            Error::Encoding { message, .. } => {
522                write!(f, "Encoding error: {message}")
523            }
524            Error::Unknown { message } => {
525                write!(f, "Unknown error: {message}")
526            }
527            Error::ToDo { message } => {
528                write!(f, "Unimplemented: {message}")
529            }
530        }
531    }
532}
533
534impl error::Error for Error {
535    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
536        match self {
537            Error::Connection { source, .. } => {
538                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
539            }
540            Error::Serialization { source, .. } => {
541                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
542            }
543            Error::Io { source, .. } => Some(source),
544            Error::HttpClient { source, .. } => {
545                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
546            }
547            Error::Url { source, .. } => {
548                source.as_ref().map(|e| e as &(dyn error::Error + 'static))
549            }
550            Error::Streaming { source, .. } => {
551                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
552            }
553            Error::Encoding { source, .. } => {
554                source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
555            }
556            _ => None,
557        }
558    }
559}
560
561impl From<io::Error> for Error {
562    fn from(err: io::Error) -> Self {
563        Error::io(err.to_string(), err)
564    }
565}
566
567impl From<serde_json::Error> for Error {
568    fn from(err: serde_json::Error) -> Self {
569        Error::serialization(format!("JSON error: {err}"), Some(Box::new(err)))
570    }
571}
572
573impl From<url::ParseError> for Error {
574    fn from(err: url::ParseError) -> Self {
575        Error::url(format!("URL parse error: {err}"), Some(err))
576    }
577}
578
579impl From<Utf8Error> for Error {
580    fn from(err: Utf8Error) -> Self {
581        Error::encoding(format!("UTF-8 error: {err}"), Some(Box::new(err)))
582    }
583}
584
585/// Maps a mid-stream SSE `error` event onto the variant the same failure gets
586/// as an HTTP error response, so retry decisions match.
587///
588/// # Example
589///
590/// ```
591/// use adk_anthropic::{ApiError, Error};
592///
593/// let error = Error::from(ApiError {
594///     error_type: "overloaded_error".to_string(),
595///     message: "Overloaded".to_string(),
596/// });
597/// assert!(error.is_retryable());
598/// ```
599impl From<crate::types::ApiError> for Error {
600    fn from(err: crate::types::ApiError) -> Self {
601        let crate::types::ApiError { error_type, message } = err;
602        match error_type.as_str() {
603            "overloaded_error" => Error::service_unavailable(message, None),
604            "rate_limit_error" => Error::rate_limit(message, None),
605            "api_error" => Error::internal_server(message, None),
606            "timeout_error" => Error::timeout(message, None),
607            "authentication_error" => Error::authentication(message),
608            "permission_error" => Error::permission(message),
609            "not_found_error" => Error::not_found(message, None, None),
610            "invalid_request_error" => Error::bad_request(message, None),
611            "billing_error" => Error::api(402, Some(error_type), message, None),
612            "request_too_large" => Error::api(413, Some(error_type), message, None),
613            _ => Error::streaming(format!("{error_type}: {message}"), None),
614        }
615    }
616}
617
618/// A specialized Result type for adk-anthropic operations.
619pub type Result<T> = std::result::Result<T, Error>;