Skip to main content

aigw_anthropic/
error.rs

1//! Error types for the Anthropic provider.
2
3use crate::transport::TransportConfigError;
4use crate::types::ApiError;
5
6/// Errors that can occur when using the Anthropic API client.
7#[derive(Debug, thiserror::Error)]
8pub enum Error {
9    /// HTTP transport error (connection, TLS, timeout via reqwest).
10    #[error("HTTP error: {0}")]
11    Http(#[from] reqwest::Error),
12
13    /// JSON serialization or deserialization error.
14    #[error("JSON error: {0}")]
15    Json(#[from] serde_json::Error),
16
17    /// Anthropic API returned a structured error response.
18    #[error("Anthropic API error ({status}): [{error_type}] {message}")]
19    Api {
20        /// HTTP status code.
21        status: u16,
22        /// Error type (e.g. `"invalid_request_error"`, `"rate_limit_error"`).
23        error_type: String,
24        /// Human-readable error message.
25        message: String,
26    },
27
28    /// Non-JSON error response from the server (e.g. 502 HTML page from a proxy).
29    #[error("unexpected error response ({status}): {body}")]
30    UnexpectedResponse {
31        /// HTTP status code.
32        status: u16,
33        /// Raw response body.
34        body: String,
35    },
36
37    /// Error from the SSE stream parser.
38    #[error("SSE stream error: {source}")]
39    Stream {
40        /// The underlying stream error.
41        #[source]
42        source: Box<dyn std::error::Error + Send + Sync>,
43    },
44
45    /// Invalid transport configuration.
46    #[error("transport config: {0}")]
47    Transport(#[from] TransportConfigError),
48
49    /// Invalid client configuration (non-transport).
50    #[error("invalid configuration: {0}")]
51    Config(String),
52}
53
54impl Error {
55    pub(crate) fn from_api_error(status: u16, error: ApiError) -> Self {
56        Self::Api {
57            status,
58            error_type: error.r#type,
59            message: error.message,
60        }
61    }
62
63    pub(crate) fn stream(err: impl std::error::Error + Send + Sync + 'static) -> Self {
64        Self::Stream {
65            source: Box::new(err),
66        }
67    }
68}