Skip to main content

aimux_core/
error.rs

1//! Error types for aimux-core.
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5use ts_rs::TS;
6
7/// Unified error type for all aimux operations.
8#[derive(Debug, Clone, Serialize, Deserialize, TS, Error)]
9#[ts(export)]
10pub enum AiMuxError {
11    #[error("provider error: {0}")]
12    Provider(String),
13
14    #[error("HTTP error: {0}")]
15    Http(String),
16
17    #[error("JSON error: {0}")]
18    Json(String),
19
20    #[error("stream error: {0}")]
21    Stream(String),
22
23    #[error("tool error: {0}")]
24    Tool(String),
25
26    #[error("invalid argument: {0}")]
27    InvalidArgument(String),
28
29    #[error("invalid prompt: {0}")]
30    InvalidPrompt(String),
31
32    #[error("rate limited: retry after {retry_after_ms}ms")]
33    RateLimited { retry_after_ms: u64 },
34
35    #[error("authentication failed: {0}")]
36    Auth(String),
37
38    #[error("model not found: {0}")]
39    ModelNotFound(String),
40
41    #[error("unsupported functionality: {0}")]
42    Unsupported(String),
43
44    #[error("no such model: {0}")]
45    NoSuchModel(String),
46
47    #[error("API call error: {0}")]
48    ApiCall(String),
49
50    #[error("{0}")]
51    Other(String),
52}
53
54impl From<serde_json::Error> for AiMuxError {
55    fn from(e: serde_json::Error) -> Self {
56        AiMuxError::Json(e.to_string())
57    }
58}
59
60impl AiMuxError {
61    /// Returns `true` if the error is transient and can be retried.
62    pub fn is_retryable(&self) -> bool {
63        matches!(
64            self,
65            AiMuxError::RateLimited { .. } | AiMuxError::Http(_) | AiMuxError::ApiCall(_)
66        )
67    }
68
69    /// Returns the retry-after delay hint (in milliseconds) carried by this
70    /// error, if any. Currently only `RateLimited` carries a hint (from a
71    /// `retry-after-ms` / `retry-after` response header). Returns `None` for
72    /// errors that don't advertise a delay, in which case the retry strategy
73    /// falls back to exponential backoff.
74    ///
75    /// Mirrors the header-consulting behaviour of
76    /// `retryWithExponentialBackoffRespectingRetryHeaders` in the TS SDK.
77    pub fn retry_after_hint(&self) -> Option<i64> {
78        match self {
79            AiMuxError::RateLimited { retry_after_ms } => Some(*retry_after_ms as i64),
80            _ => None,
81        }
82    }
83
84    /// Returns the error variant name as a string (e.g. `"Auth"`, `"Provider"`,
85    /// `"RateLimited"`). Used by FFI bindings to give callers a machine-readable
86    /// error type alongside the human-readable message.
87    pub fn error_type(&self) -> &'static str {
88        match self {
89            AiMuxError::Provider(_) => "Provider",
90            AiMuxError::Http(_) => "Http",
91            AiMuxError::Json(_) => "Json",
92            AiMuxError::Stream(_) => "Stream",
93            AiMuxError::Tool(_) => "Tool",
94            AiMuxError::InvalidArgument(_) => "InvalidArgument",
95            AiMuxError::InvalidPrompt(_) => "InvalidPrompt",
96            AiMuxError::RateLimited { .. } => "RateLimited",
97            AiMuxError::Auth(_) => "Auth",
98            AiMuxError::ModelNotFound(_) => "ModelNotFound",
99            AiMuxError::Unsupported(_) => "Unsupported",
100            AiMuxError::NoSuchModel(_) => "NoSuchModel",
101            AiMuxError::ApiCall(_) => "ApiCall",
102            AiMuxError::Other(_) => "Other",
103        }
104    }
105
106    /// Returns the HTTP status code carried by this error, if any.
107    ///
108    /// HTTP-layer errors created by `parse_provider_error` and
109    /// `send_with_retry_raw` embed the status code in the message as
110    /// `"HTTP {status}: ..."`. This method extracts it. Errors that don't
111    /// originate from an HTTP response return `None`.
112    pub fn status_code(&self) -> Option<u16> {
113        let message = match self {
114            AiMuxError::Provider(m)
115            | AiMuxError::Http(m)
116            | AiMuxError::Auth(m)
117            | AiMuxError::ApiCall(m)
118            | AiMuxError::ModelNotFound(m) => m,
119            _ => return None,
120        };
121        // Parse "HTTP 403: ..." → 403
122        let rest = message.strip_prefix("HTTP ")?;
123        let code_str: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
124        code_str.parse().ok()
125    }
126}