1use serde::{Deserialize, Serialize};
4use thiserror::Error;
5use ts_rs::TS;
6
7#[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 pub fn is_retryable(&self) -> bool {
63 matches!(
64 self,
65 AiMuxError::RateLimited { .. } | AiMuxError::Http(_) | AiMuxError::ApiCall(_)
66 )
67 }
68
69 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 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 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 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}