1use std::fmt;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ErrorCode {
22 InvalidInput = 1001,
24 MissingParameter = 1002,
26 Cancelled = 1003,
28 Timeout = 1004,
30 NotImplemented = 1005,
32 UnsupportedConfig = 1006,
34
35 ToolNotFound = 2001,
37 ToolValidation = 2002,
39 ToolExecution = 2003,
41 ToolSandboxed = 2004,
43
44 PermissionDenied = 3001,
46 PathNotAllowed = 3002,
48 NetworkBlocked = 3003,
50
51 HttpClientError = 4001,
53 HttpServerError = 4002,
55 ApiUnauthorized = 4003,
57 ApiRateLimited = 4004,
59 ConnectionTimeout = 4005,
61 ConnectionFailed = 4006,
63
64 FileNotFound = 5001,
66 FileReadError = 5002,
68 FileWriteError = 5003,
70 FilePermission = 5004,
72 InvalidPath = 5005,
74 DiskFull = 5006,
76
77 SessionNotFound = 6001,
79 SessionExpired = 6002,
81 SessionCapReached = 6003,
83 TranscriptCorrupt = 6004,
85
86 ModelUnsupportedParam = 7001,
88 ContextWindowExceeded = 7002,
90 ModelParseError = 7003,
92 ModelEmptyResponse = 7004,
94 StreamAborted = 7005,
96
97 McpConnectFailed = 8001,
99 McpToolCallFailed = 8002,
101 McpOAuthFailed = 8003,
103
104 InternalInconsistency = 9001,
106 ChannelClosed = 9002,
108 Internal = 9999,
110}
111
112impl ErrorCode {
113 pub fn label(self) -> &'static str {
115 match self {
116 Self::InvalidInput => "invalid input",
117 Self::MissingParameter => "missing parameter",
118 Self::Cancelled => "cancelled",
119 Self::Timeout => "timeout",
120 Self::NotImplemented => "not implemented",
121 Self::UnsupportedConfig => "unsupported config",
122 Self::ToolNotFound => "tool not found",
123 Self::ToolValidation => "tool validation failed",
124 Self::ToolExecution => "tool execution failed",
125 Self::ToolSandboxed => "tool blocked by sandbox",
126 Self::PermissionDenied => "permission denied",
127 Self::PathNotAllowed => "path not allowed",
128 Self::NetworkBlocked => "network blocked by policy",
129 Self::HttpClientError => "HTTP client error",
130 Self::HttpServerError => "HTTP server error",
131 Self::ApiUnauthorized => "API unauthorized",
132 Self::ApiRateLimited => "API rate limited",
133 Self::ConnectionTimeout => "connection timeout",
134 Self::ConnectionFailed => "connection failed",
135 Self::FileNotFound => "file not found",
136 Self::FileReadError => "file read error",
137 Self::FileWriteError => "file write error",
138 Self::FilePermission => "file permission denied",
139 Self::InvalidPath => "invalid path",
140 Self::DiskFull => "disk full",
141 Self::SessionNotFound => "session not found",
142 Self::SessionExpired => "session expired",
143 Self::SessionCapReached => "session capacity reached",
144 Self::TranscriptCorrupt => "transcript corrupt",
145 Self::ModelUnsupportedParam => "model unsupported parameter",
146 Self::ContextWindowExceeded => "context window exceeded",
147 Self::ModelParseError => "model response parse error",
148 Self::ModelEmptyResponse => "model returned empty response",
149 Self::StreamAborted => "stream aborted",
150 Self::McpConnectFailed => "MCP connect failed",
151 Self::McpToolCallFailed => "MCP tool call failed",
152 Self::McpOAuthFailed => "MCP OAuth failed",
153 Self::InternalInconsistency => "internal state inconsistency",
154 Self::ChannelClosed => "channel closed",
155 Self::Internal => "internal error",
156 }
157 }
158
159 pub fn code(self) -> u16 {
161 self as u16
162 }
163}
164
165impl fmt::Display for ErrorCode {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 write!(f, "[E{:04}] {}", self.code(), self.label())
168 }
169}
170
171#[derive(Debug)]
176pub struct CodedError {
177 pub code: ErrorCode,
178 pub message: String,
179 pub source: Option<anyhow::Error>,
181}
182
183impl CodedError {
184 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
185 Self {
186 code,
187 message: message.into(),
188 source: None,
189 }
190 }
191
192 pub fn with_source(code: ErrorCode, message: impl Into<String>, source: anyhow::Error) -> Self {
193 Self {
194 code,
195 message: message.into(),
196 source: Some(source),
197 }
198 }
199
200 pub fn diagnostic(&self) -> String {
202 let mut s = format!("[E{:04}] {}", self.code.code(), self.message);
203 if let Some(ref src) = self.source {
204 s.push_str(&format!("\n caused by: {src}"));
205 }
206 s
207 }
208}
209
210impl fmt::Display for CodedError {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 write!(f, "[E{:04}] {}", self.code.code(), self.message)
213 }
214}
215
216impl std::error::Error for CodedError {
217 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
218 self.source
219 .as_ref()
220 .map(|e| e.as_ref() as &dyn std::error::Error)
221 }
222}
223
224#[cfg(test)]
228mod tests {
229 use super::*;
230
231 #[test]
232 fn every_code_has_label() {
233 let codes = &[
235 ErrorCode::InvalidInput,
236 ErrorCode::MissingParameter,
237 ErrorCode::Cancelled,
238 ErrorCode::Timeout,
239 ErrorCode::NotImplemented,
240 ErrorCode::UnsupportedConfig,
241 ErrorCode::ToolNotFound,
242 ErrorCode::ToolValidation,
243 ErrorCode::ToolExecution,
244 ErrorCode::ToolSandboxed,
245 ErrorCode::PermissionDenied,
246 ErrorCode::PathNotAllowed,
247 ErrorCode::NetworkBlocked,
248 ErrorCode::HttpClientError,
249 ErrorCode::HttpServerError,
250 ErrorCode::ApiUnauthorized,
251 ErrorCode::ApiRateLimited,
252 ErrorCode::ConnectionTimeout,
253 ErrorCode::ConnectionFailed,
254 ErrorCode::FileNotFound,
255 ErrorCode::FileReadError,
256 ErrorCode::FileWriteError,
257 ErrorCode::FilePermission,
258 ErrorCode::InvalidPath,
259 ErrorCode::DiskFull,
260 ErrorCode::SessionNotFound,
261 ErrorCode::SessionExpired,
262 ErrorCode::SessionCapReached,
263 ErrorCode::TranscriptCorrupt,
264 ErrorCode::ModelUnsupportedParam,
265 ErrorCode::ContextWindowExceeded,
266 ErrorCode::ModelParseError,
267 ErrorCode::ModelEmptyResponse,
268 ErrorCode::StreamAborted,
269 ErrorCode::McpConnectFailed,
270 ErrorCode::McpToolCallFailed,
271 ErrorCode::McpOAuthFailed,
272 ErrorCode::InternalInconsistency,
273 ErrorCode::ChannelClosed,
274 ErrorCode::Internal,
275 ];
276 for &c in codes {
277 assert!(!c.label().is_empty(), "{c:?} missing label");
278 assert!(c.code() >= 1001, "{c:?} code out of range");
279 assert!(
280 format!("{c}").contains(&format!("E{:04}", c.code())),
281 "{c:?} Display format wrong"
282 );
283 }
284 assert!(
286 codes.len() >= 39,
287 "expected at least 39 codes, got {}",
288 codes.len()
289 );
290 }
291
292 #[test]
293 fn coded_error_display() {
294 let e = CodedError::new(ErrorCode::FileNotFound, "no such file: /tmp/x");
295 assert_eq!(e.to_string(), "[E5001] no such file: /tmp/x");
296 }
297
298 #[test]
299 fn coded_error_diagnostic_includes_source() {
300 let inner = anyhow::anyhow!("permission denied");
301 let e = CodedError::with_source(ErrorCode::FileReadError, "read failed", inner);
302 let diag = e.diagnostic();
303 assert!(diag.contains("E5002"));
304 assert!(diag.contains("read failed"));
305 assert!(diag.contains("permission denied"));
306 }
307
308 #[test]
309 fn coded_error_into_anyhow() {
310 let e = CodedError::new(ErrorCode::Timeout, "timed out");
311 let a: anyhow::Error = e.into();
312 assert!(a.to_string().contains("E1004"));
313 }
314
315 #[test]
316 fn error_code_prefixes_cover_all_categories() {
317 let all_codes = &[
319 ErrorCode::InvalidInput,
320 ErrorCode::ToolNotFound,
321 ErrorCode::PermissionDenied,
322 ErrorCode::HttpClientError,
323 ErrorCode::FileNotFound,
324 ErrorCode::SessionNotFound,
325 ErrorCode::ModelUnsupportedParam,
326 ErrorCode::McpConnectFailed,
327 ErrorCode::Internal,
328 ];
329 let categories: std::collections::HashSet<u16> =
330 all_codes.iter().map(|c| c.code() / 1000).collect();
331 for cat in 1..=9 {
332 assert!(categories.contains(&cat), "missing error category {cat}xxx");
333 }
334 }
335}