Skip to main content

base/error/
code.rs

1//! 统一错误码体系。
2//!
3//! 每个可观测的错误都分配一个唯一错误码。错误码跨 crate 稳定,
4//! 上层可以据此做 i18n / 监控告警 / 降级策略。
5
6use std::fmt;
7
8/// 全局错误码。
9///
10/// 编码规则:
11/// - `1xxx` — 通用 / 输入验证
12/// - `2xxx` — 工具执行
13/// - `3xxx` — 权限 / 安全
14/// - `4xxx` — 网络 / API
15/// - `5xxx` — 文件 / IO
16/// - `6xxx` — 会话 / 状态
17/// - `7xxx` — 模型 / LLM
18/// - `8xxx` — MCP 协议
19/// - `9xxx` — 内部 / 未分类
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ErrorCode {
22    /// 输入格式不符合预期
23    InvalidInput = 1001,
24    /// 缺少必填参数
25    MissingParameter = 1002,
26    /// 操作被用户取消
27    Cancelled = 1003,
28    /// 操作超时
29    Timeout = 1004,
30    /// 功能未实现
31    NotImplemented = 1005,
32    /// 不支持的配置
33    UnsupportedConfig = 1006,
34
35    /// 工具未找到
36    ToolNotFound = 2001,
37    /// 工具输入校验失败
38    ToolValidation = 2002,
39    /// 工具执行失败
40    ToolExecution = 2003,
41    /// 工具被沙箱拒绝
42    ToolSandboxed = 2004,
43
44    /// 权限拒绝
45    PermissionDenied = 3001,
46    /// 路径不在允许范围内
47    PathNotAllowed = 3002,
48    /// 网络访问被策略阻止
49    NetworkBlocked = 3003,
50
51    /// HTTP 客户端错误 (4xx)
52    HttpClientError = 4001,
53    /// HTTP 服务端错误 (5xx)
54    HttpServerError = 4002,
55    /// API 认证失败
56    ApiUnauthorized = 4003,
57    /// API 限流
58    ApiRateLimited = 4004,
59    /// 连接超时
60    ConnectionTimeout = 4005,
61    /// DNS / TCP 连接失败
62    ConnectionFailed = 4006,
63
64    /// 文件不存在
65    FileNotFound = 5001,
66    /// 文件读取失败
67    FileReadError = 5002,
68    /// 文件写入失败
69    FileWriteError = 5003,
70    /// 文件权限不足
71    FilePermission = 5004,
72    /// 路径格式不合法
73    InvalidPath = 5005,
74    /// 磁盘空间不足
75    DiskFull = 5006,
76
77    /// 会话不存在
78    SessionNotFound = 6001,
79    /// 会话已过期
80    SessionExpired = 6002,
81    /// 会话达到上限
82    SessionCapReached = 6003,
83    /// JSONL 格式错误
84    TranscriptCorrupt = 6004,
85
86    /// 模型不支持的参数
87    ModelUnsupportedParam = 7001,
88    /// token 超出上下文窗口
89    ContextWindowExceeded = 7002,
90    /// 模型响应解析失败
91    ModelParseError = 7003,
92    /// 模型返回空响应
93    ModelEmptyResponse = 7004,
94    /// 流意外终止
95    StreamAborted = 7005,
96
97    /// MCP 服务连接失败
98    McpConnectFailed = 8001,
99    /// MCP 工具调用失败
100    McpToolCallFailed = 8002,
101    /// MCP OAuth 流程失败
102    McpOAuthFailed = 8003,
103
104    /// 内部状态不一致
105    InternalInconsistency = 9001,
106    /// channel 发送端断开
107    ChannelClosed = 9002,
108    /// 未分类的内部错误
109    Internal = 9999,
110}
111
112impl ErrorCode {
113    /// 人类可读的简短标签(英文,一行)。
114    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    /// 错误码数值。
160    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/// 带错误码的通用错误载体。
172///
173/// 所有可以通过 crate 边界传播的错误都应包装为 `CodedError`,
174/// 确保接收方可以拿到稳定的错误码而不是解析字符串。
175#[derive(Debug)]
176pub struct CodedError {
177    pub code: ErrorCode,
178    pub message: String,
179    /// 可选的底层错误(用于日志 / 调试,不进入用户可见消息)。
180    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    /// 仅用于日志的诊断字符串(含 source chain)。
201    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// CodedError 实现了 std::error::Error,anyhow 的 blanket From<E> 自动覆盖,
225// 无需手动实现 From<CodedError> for anyhow::Error。
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn every_code_has_label() {
233        // 覆盖所有变体,确保 match 无遗漏
234        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        // ensure every variant is covered (count may grow as codes are added)
285        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        // Verify that all 9 major categories (1xxx–9xxx) are used by at least one code
318        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}