Skip to main content

yang_base/error/
mod.rs

1//! 错误处理模块
2//!
3//! 定义系统中所有模块使用的统一错误类型。
4//!
5//! # 主要组件
6//!
7//! - `BaseError`:统一错误枚举类型
8//!
9//! # 示例
10//!
11//! ```rust,ignore
12//! use yang_base::error::BaseError;
13//!
14//! fn do_something() -> Result<(), BaseError> {
15//!     // 插件未找到错误
16//!     Err(BaseError::PluginNotFound("my_plugin".to_string()))
17//! }
18//! ```
19
20use thiserror::Error;
21
22/// 以 [`BaseError`] 为默认错误类型的统一 `Result` 别名。
23///
24/// 允许下游以 `yang_base::Result<T>` 书写返回类型,省去重复的 `, BaseError`。
25/// 保留类型参数 `E = BaseError`,少数需要其它错误类型的签名仍可显式覆盖。
26pub type Result<T, E = BaseError> = std::result::Result<T, E>;
27
28/// 系统统一错误类型
29///
30/// 包含所有模块的错误变体,使用中文错误消息
31///
32/// 标注 `#[non_exhaustive]`:未来新增变体不构成跨 crate 破坏性变更(下游 match 需
33/// 带 `_` 臂)。同 crate 内的穷举 match(`code()`/`code_str()`/`category()`)不受
34/// 影响,新增变体时 `test_code_str_matches_code` 测试会捕获漏编。
35#[derive(Debug, Error)]
36#[non_exhaustive]
37pub enum BaseError {
38    // ==================== 插件管理错误 ====================
39    /// 插件已注册
40    #[error("插件已注册: {0}")]
41    PluginAlreadyRegistered(String),
42
43    /// 插件未找到
44    #[error("插件未找到: {0}")]
45    PluginNotFound(String),
46
47    /// 插件注册失败
48    #[error("插件注册失败 [{0}]: {1}")]
49    PluginRegisterFailed(String, String),
50
51    /// 插件初始化失败
52    #[error("插件初始化失败 [{0}]: {1}")]
53    PluginInitFailed(String, String),
54
55    /// 插件依赖缺失
56    #[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
57    PluginDependencyMissing(String, String),
58
59    /// 插件循环依赖
60    #[error("插件循环依赖: {0}")]
61    PluginCircularDependency(String),
62
63    /// 插件配置无效
64    #[error("插件配置无效 [{0}]: {1}")]
65    PluginConfigInvalid(String, String),
66
67    /// 插件关闭失败
68    #[error("插件关闭失败 [{0}]: {1}")]
69    PluginShutdownFailed(String, String),
70
71    /// 插件生命周期回调失败,保留插件名、阶段与底层错误链。
72    #[error("插件生命周期失败 [{plugin}] ({stage}): {source}")]
73    PluginLifecycleFailed {
74        /// 插件名称。
75        plugin: String,
76        /// 失败阶段。
77        stage: crate::plugin::PluginLifecycleStage,
78        /// 插件回调或初始化操作返回的底层错误。
79        #[source]
80        source: crate::plugin::PluginError,
81    },
82
83    // ==================== 数据库错误 ====================
84    /// 数据库连接失败,持有底层 DbError 以保留错误链
85    #[error("数据库连接失败 [DbError]: {0}")]
86    DatabaseConnectionFailed(#[source] yang_db::DbError),
87
88    /// 数据库连接失败(DbError 专用变体,用于 `From<DbError>` 映射)
89    ///
90    /// 与 `DatabaseConnectionFailed` 语义相同但独立编码 200011,
91    /// 便于下游区分"直接构造的连接错误"和"来自 DbError 包装的连接错误"。
92    #[error("数据库连接失败 [DbError]: {0}")]
93    DatabaseConnectionDbError(#[source] yang_db::DbError),
94
95    /// 数据库已初始化
96    #[error("数据库已初始化")]
97    DatabaseAlreadyInitialized,
98
99    /// 数据库查询失败,持有底层 DbError 以保留错误链
100    #[error("数据库查询失败: {0}")]
101    DatabaseQueryFailed(#[source] yang_db::DbError),
102
103    /// 数据库执行失败,持有底层 DbError 以保留错误链
104    #[error("数据库执行失败: {0}")]
105    DatabaseExecuteFailed(#[source] yang_db::DbError),
106
107    /// 数据库初始化失败
108    #[error("数据库初始化失败: {0}")]
109    DatabaseInitFailed(String),
110
111    /// 数据库未初始化
112    #[error("数据库未初始化")]
113    DatabaseNotInitialized,
114
115    /// 数据库事务失败,持有底层 DbError 以保留错误链
116    #[error("数据库事务失败: {0}")]
117    DatabaseTransactionFailed(#[source] yang_db::DbError),
118
119    /// UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作
120    ///
121    /// 与 yang-db 的 `MissingWhereClause` 安全网对齐:无 WHERE 的更新/删除
122    /// 始终被拒绝,以防止误操作整表。
123    #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
124    MissingWhereClause(String),
125
126    // ==================== Redis 错误 ====================
127    /// Redis 连接失败,持有底层 DbError 以保留错误链。
128    #[error("Redis 连接失败: {0}")]
129    RedisConnectionFailed(#[source] yang_db::DbError),
130
131    /// Redis 已初始化
132    #[error("Redis 已初始化")]
133    RedisAlreadyInitialized,
134
135    /// Redis 未初始化
136    #[error("Redis 未初始化")]
137    RedisNotInitialized,
138
139    /// Redis 操作失败,持有底层 DbError 以保留错误链。
140    #[error("Redis 操作失败: {0}")]
141    RedisOperationFailed(#[source] yang_db::DbError),
142
143    /// Redis 操作失败,持有底层 DbError 以保留错误链
144    #[error("Redis 操作失败: {0}")]
145    RedisOperationDbError(#[source] yang_db::DbError),
146
147    // ==================== HTTP 客户端错误 ====================
148    /// HTTP 客户端创建失败,持有底层 reqwest::Error 以保留错误链
149    #[cfg(feature = "http")]
150    #[error("HTTP 客户端创建失败: {0}")]
151    HttpClientCreateFailed(#[source] reqwest::Error),
152
153    /// HTTP 客户端创建失败(无 http feature 时使用字符串)
154    #[cfg(not(feature = "http"))]
155    #[error("HTTP 客户端创建失败: {0}")]
156    HttpClientCreateFailed(String),
157
158    /// HTTP 请求失败,持有底层 reqwest::Error 以保留错误链
159    #[cfg(feature = "http")]
160    #[error("HTTP 请求失败: {0}")]
161    HttpRequestFailed(#[source] reqwest::Error),
162
163    /// HTTP 请求失败(无 http feature 时使用字符串)
164    #[cfg(not(feature = "http"))]
165    #[error("HTTP 请求失败: {0}")]
166    HttpRequestFailed(String),
167
168    /// HTTP 响应解析失败
169    #[error("HTTP 响应解析失败: {0}")]
170    HttpResponseParseFailed(String),
171
172    /// HTTP 超时
173    #[error("HTTP 请求超时")]
174    HttpTimeout,
175
176    /// HTTP 客户端已初始化
177    #[error("HTTP 客户端已初始化")]
178    HttpClientAlreadyInitialized,
179
180    /// HTTP 客户端未初始化
181    #[error("HTTP 客户端未初始化")]
182    HttpClientNotInitialized,
183
184    /// HTTP 熔断器打开:目标 host 近期连续失败,请求被快速拒绝
185    #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
186    HttpCircuitBreakerOpen(String),
187
188    // ==================== Token 管理错误 ====================
189    /// Token 密钥无效
190    #[error("Token 密钥无效: {0}")]
191    TokenKeyInvalid(String),
192
193    /// Token 生成失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
194    #[cfg(feature = "token")]
195    #[error("Token 生成失败: {0}")]
196    TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
197
198    /// Token 生成失败(无 token feature 时使用字符串)
199    #[cfg(not(feature = "token"))]
200    #[error("Token 生成失败: {0}")]
201    TokenGenerateFailed(String),
202
203    /// Token 验证失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
204    #[cfg(feature = "token")]
205    #[error("Token 验证失败: {0}")]
206    TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
207
208    /// Token 验证失败(无 token feature 时使用字符串)
209    #[cfg(not(feature = "token"))]
210    #[error("Token 验证失败: {0}")]
211    TokenVerifyFailed(String),
212
213    /// Token 解析失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
214    #[cfg(feature = "token")]
215    #[error("Token 解析失败: {0}")]
216    TokenParseFailed(#[source] jsonwebtoken::errors::Error),
217
218    /// Token 解析失败(无 token feature 时使用字符串)
219    #[cfg(not(feature = "token"))]
220    #[error("Token 解析失败: {0}")]
221    TokenParseFailed(String),
222
223    /// Token 已过期
224    #[error("Token 已过期")]
225    TokenExpired,
226
227    /// Token 已被撤销(命中黑名单)
228    #[error("Token 已被撤销")]
229    TokenRevoked,
230
231    /// Token 撤销状态损坏或返回结构不符合协议。
232    #[error("Token 撤销状态无效: {0}")]
233    TokenRevocationStateInvalid(String),
234
235    /// Access Token 中的授权版本已落后于当前事实版本。
236    #[error("授权状态已变更,请刷新登录")]
237    AuthorizationStale,
238
239    /// Access Token 中的授权版本缺失、非法或领先于事实版本。
240    #[error("授权版本无效")]
241    AuthorizationVersionInvalid,
242
243    /// 授权版本缓存与事实存储均无法完成请求时校验。
244    #[error("授权状态暂时无法校验")]
245    AuthorizationCheckUnavailable,
246
247    /// Token 类型无效
248    #[error("Token 类型无效: {0}")]
249    TokenTypeInvalid(String),
250
251    // ==================== 序列化错误 ====================
252    /// JSON 序列化失败
253    #[error("JSON 序列化失败: {0}")]
254    JsonSerializeFailed(String),
255
256    /// JSON 反序列化失败
257    #[error("JSON 反序列化失败: {0}")]
258    JsonDeserializeFailed(String),
259
260    // ==================== 字段验证错误 ====================
261    /// 字段类型无效
262    #[error("字段类型无效 [{0}]: {1}")]
263    InvalidFieldType(String, String),
264
265    /// 枚举值无效
266    #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
267    InvalidEnumValue(String, String),
268
269    /// 字符串长度超出限制
270    #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
271    StringTooLong(String, usize, usize),
272
273    /// JSON 格式无效
274    #[error("JSON 格式无效 [{0}]: {1}")]
275    InvalidJsonFormat(String, String),
276
277    /// 验证失败
278    #[error("验证失败 [{0}]: {1}")]
279    ValidationFailed(String, String),
280
281    /// 字段必填
282    #[error("字段必填: {0}")]
283    FieldRequired(String),
284
285    /// 字段未找到
286    #[error("字段未找到 [表: {0}]: {1}")]
287    FieldNotFound(String, String),
288
289    /// 字段权限被拒绝
290    #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
291    FieldPermissionDenied(String, String, String),
292
293    // ==================== Action 系统错误 ====================
294    /// Action 未找到
295    #[error("Action 未找到: {0}")]
296    ActionNotFound(String),
297
298    /// 权限被拒绝
299    #[error("权限被拒绝: {0}")]
300    PermissionDenied(String),
301
302    /// 未授权
303    #[error("未授权: {0}")]
304    Unauthorized(String),
305
306    /// 参数缺失
307    #[error("参数缺失: {0}")]
308    ParamMissing(String),
309
310    /// 参数无效
311    #[error("参数无效 [{0}]: {1}")]
312    ParamInvalid(String, String),
313
314    /// 请求超过速率限制。
315    #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
316    RateLimitExceeded {
317        /// 建议客户端等待的秒数。
318        retry_after_seconds: u64,
319    },
320
321    /// 记录未找到
322    #[error("记录未找到: {0}")]
323    RecordNotFound(String),
324
325    /// 用户未找到
326    #[error("用户未找到: {0}")]
327    UserNotFound(String),
328
329    /// 密码无效
330    #[error("密码无效")]
331    InvalidPassword,
332
333    /// 表定义未设置
334    #[error("表定义未设置")]
335    TableDefinitionNotSet,
336
337    /// 敏感 Action 尚未完成短期重认证。
338    #[cfg(feature = "token")]
339    #[error("敏感操作需要重新认证")]
340    StepUpRequired(crate::action::StepUpChallenge),
341
342    // ==================== 通用错误 ====================
343    /// 配置错误
344    #[error("配置错误: {0}")]
345    ConfigError(String),
346
347    /// IO 错误
348    #[error("IO 错误: {0}")]
349    IoError(String),
350
351    /// 未知错误
352    #[error("未知错误: {0}")]
353    Unknown(String),
354}
355
356// ==================== From trait 实现 ====================
357
358/// 从 yang_db::DbError 转换为 BaseError
359///
360/// 按 DbError 变体分类映射到对应的 BaseError 变体:
361/// - 查询类 → DatabaseQueryFailed
362/// - 执行类 → DatabaseExecuteFailed
363/// - 事务类 → DatabaseTransactionFailed
364/// - 连接类 → DatabaseConnectionFailed(包装 DbError 保留错误链)
365/// - Redis 连接类 → RedisConnectionFailed
366/// - Redis 其他操作类 → RedisOperationFailed
367#[allow(unreachable_patterns)]
368impl From<yang_db::DbError> for BaseError {
369    fn from(err: yang_db::DbError) -> Self {
370        use yang_db::DbError as D;
371        match &err {
372            // 查询类:查询错误、表不存在、类型转换、反序列化、不支持的操作符、未知错误
373            D::QueryError(_)
374            | D::TableNotFound(_)
375            | D::TypeConversionError(_)
376            | D::DeserializationError(_)
377            | D::UnsupportedOperator(_)
378            | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
379
380            // 执行类:约束错误、SQL 语法错误、缺少 WHERE 条件、缺少 GROUP BY、序列化错误、参数非法
381            D::ConstraintError(_)
382            | D::SqlSyntaxError(_)
383            | D::MissingWhereClause
384            | D::MissingGroupByClause
385            | D::InvalidArgument(_)
386            | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
387
388            // 事务类:事务错误
389            D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
390
391            // 连接类:连接错误(保留底层 DbError 错误链)→ DatabaseConnectionDbError (200011)
392            D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
393
394            // Redis 连接类:保留底层 DbError 错误链
395            D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
396
397            // Redis 操作类:保留底层 DbError 错误链
398            D::RedisCommandError(_)
399            | D::RedisPoolError(_)
400            | D::RedisTypeConversionError(_)
401            | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
402
403            // 未来新增变体(DbError 标注 #[non_exhaustive])统一按查询失败处理
404            _ => BaseError::DatabaseQueryFailed(err),
405        }
406    }
407}
408
409/// 从 std::io::Error 转换为 BaseError
410impl From<std::io::Error> for BaseError {
411    fn from(err: std::io::Error) -> Self {
412        BaseError::IoError(err.to_string())
413    }
414}
415
416/// 从 serde_json::Error 转换为 BaseError
417impl From<serde_json::Error> for BaseError {
418    fn from(err: serde_json::Error) -> Self {
419        if err.is_syntax() || err.is_data() || err.is_eof() {
420            BaseError::JsonDeserializeFailed(err.to_string())
421        } else {
422            BaseError::JsonSerializeFailed(err.to_string())
423        }
424    }
425}
426
427/// 从 reqwest::Error 转换为 BaseError
428#[cfg(feature = "http")]
429impl From<reqwest::Error> for BaseError {
430    fn from(err: reqwest::Error) -> Self {
431        if err.is_timeout() {
432            BaseError::HttpTimeout
433        } else {
434            // is_connect() 属于「发送请求」阶段的连接失败(DNS/TCP/TLS),
435            // 客户端此时早已创建成功,故与其它发送错误统一归为 HttpRequestFailed。
436            // 真正的客户端创建失败由 http/client.rs 显式 map_err(HttpClientCreateFailed) 处理。
437            BaseError::HttpRequestFailed(err)
438        }
439    }
440}
441
442/// 从 jsonwebtoken::errors::Error 转换为 BaseError
443///
444/// 按 ErrorKind 分类映射:
445/// - ExpiredSignature → TokenExpired
446/// - InvalidToken / InvalidSignature → TokenVerifyFailed
447/// - 其他 → TokenParseFailed
448#[cfg(feature = "token")]
449impl From<jsonwebtoken::errors::Error> for BaseError {
450    fn from(err: jsonwebtoken::errors::Error) -> Self {
451        use jsonwebtoken::errors::ErrorKind;
452        match err.kind() {
453            ErrorKind::ExpiredSignature => BaseError::TokenExpired,
454            ErrorKind::InvalidToken
455            | ErrorKind::InvalidSignature
456            | ErrorKind::InvalidIssuer
457            | ErrorKind::InvalidAudience
458            | ErrorKind::InvalidSubject
459            | ErrorKind::InvalidAlgorithm
460            | ErrorKind::MissingAlgorithm
461            | ErrorKind::ImmatureSignature
462            | ErrorKind::MissingRequiredClaim(_)
463            | ErrorKind::InvalidEcdsaKey
464            | ErrorKind::InvalidRsaKey(_)
465            | ErrorKind::InvalidKeyFormat
466            | ErrorKind::RsaFailedSigning
467            | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
468            // 真正解析/IO 错误 → TokenParseFailed
469            ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
470                BaseError::TokenParseFailed(err)
471            }
472            // 防非穷尽: 未显式列出的验证类错误 → TokenVerifyFailed
473            _ => BaseError::TokenVerifyFailed(err),
474        }
475    }
476}
477
478/// 引擎级错误分类(与具体 HTTP/传输层无关)。
479///
480/// 用于下游统一适配(弹性重试、错误上报分桶、HTTP status 映射的中间层)。
481/// HTTP status 映射属调用方传输层边界,不在引擎层硬编码。
482///
483/// `is_client_error()` = `Client` + `Auth` + `NotFound`;`is_server_error()` = `Server` +
484/// `Transient` + `Conflict`。详见 [`BaseError::category`] 文档。
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486#[non_exhaustive]
487pub enum ErrorCategory {
488    /// 调用方过错(参数错误、字段验证、序列化、插件依赖/配置/循环)
489    Client,
490    /// 认证/授权失败(登录过期、Token 撤销、密码错误、权限不足)
491    Auth,
492    /// 资源不存在(记录/用户/Action/表未找到)
493    NotFound,
494    /// 资源冲突(插件注册冲突)
495    Conflict,
496    /// 瞬时故障(连接失败/超时/连接池/HTTP 超时/熔断打开),可重试
497    ///
498    /// 在 `is_server_error` 中视为服务端错误(可重试的服务端故障,
499    /// 如连接超时 = HTTP 503 语义),但 `is_client_error` 中**不**视为客户端错误。
500    Transient,
501    /// 服务端/基础设施错误(内部失败、配置错误、未知错误)
502    Server,
503}
504
505impl BaseError {
506    /// 获取错误码
507    ///
508    /// 返回与错误类型对应的数字错误码,用于 API 响应
509    ///
510    /// # 错误码规范
511    ///
512    /// - 1xxxxx: 插件管理错误
513    /// - 2xxxxx: 数据库错误
514    ///   - 21xxxx: Redis 错误(隶属数据库 2xxxxx 大类)
515    /// - 3xxxxx: HTTP 客户端错误
516    /// - 4xxxxx: Token 管理错误
517    /// - 5xxxxx: 序列化错误
518    /// - 6xxxxx: 字段验证错误
519    /// - 7xxxxx: Action 系统错误
520    /// - 9xxxxx: 通用错误
521    ///
522    /// # 返回
523    ///
524    /// - 错误码(非零整数)
525    ///
526    /// # 示例
527    ///
528    /// ```rust,ignore
529    /// use yang_base::error::BaseError;
530    ///
531    /// let error = BaseError::FieldRequired("username".to_string());
532    /// assert_eq!(error.code(), 600006);
533    /// ```
534    pub fn code(&self) -> i32 {
535        match self {
536            // ==================== 插件管理错误 (1xxxxx) ====================
537            BaseError::PluginAlreadyRegistered(_) => 100001,
538            BaseError::PluginNotFound(_) => 100002,
539            BaseError::PluginRegisterFailed(_, _) => 100003,
540            BaseError::PluginInitFailed(_, _) => 100004,
541            BaseError::PluginDependencyMissing(_, _) => 100005,
542            BaseError::PluginCircularDependency(_) => 100006,
543            BaseError::PluginConfigInvalid(_, _) => 100007,
544            BaseError::PluginShutdownFailed(_, _) => 100008,
545            BaseError::PluginLifecycleFailed { stage, .. } => match stage {
546                crate::plugin::PluginLifecycleStage::Register => 100003,
547                crate::plugin::PluginLifecycleStage::Initialize => 100004,
548                crate::plugin::PluginLifecycleStage::Shutdown => 100008,
549            },
550
551            // ==================== 数据库错误 (2xxxxx) ====================
552            BaseError::DatabaseConnectionFailed(_) => 200001,
553            BaseError::DatabaseConnectionDbError(_) => 200011,
554            BaseError::DatabaseAlreadyInitialized => 200002,
555            BaseError::DatabaseQueryFailed(_) => 200003,
556            BaseError::DatabaseExecuteFailed(_) => 200004,
557            BaseError::DatabaseInitFailed(_) => 200005,
558            BaseError::DatabaseNotInitialized => 200008,
559            BaseError::DatabaseTransactionFailed(_) => 200009,
560            BaseError::MissingWhereClause(_) => 200010,
561
562            // ==================== Redis 错误 (21xxxx) ====================
563            BaseError::RedisConnectionFailed(_) => 210001,
564            BaseError::RedisAlreadyInitialized => 210002,
565            BaseError::RedisNotInitialized => 210003,
566            BaseError::RedisOperationFailed(_) => 210004,
567            BaseError::RedisOperationDbError(_) => 210011,
568
569            // ==================== HTTP 客户端错误 (3xxxxx) ====================
570            BaseError::HttpClientCreateFailed(_) => 300001,
571            BaseError::HttpRequestFailed(_) => 300002,
572            BaseError::HttpResponseParseFailed(_) => 300003,
573            BaseError::HttpTimeout => 300004,
574            BaseError::HttpClientAlreadyInitialized => 300005,
575            BaseError::HttpClientNotInitialized => 300006,
576            BaseError::HttpCircuitBreakerOpen(_) => 300007,
577
578            // ==================== Token 管理错误 (4xxxxx) ====================
579            BaseError::TokenKeyInvalid(_) => 400001,
580            BaseError::TokenGenerateFailed(_) => 400002,
581            BaseError::TokenVerifyFailed(_) => 400003,
582            BaseError::TokenParseFailed(_) => 400004,
583            BaseError::TokenExpired => 400005,
584            BaseError::TokenTypeInvalid(_) => 400006,
585            BaseError::TokenRevoked => 400007,
586            BaseError::TokenRevocationStateInvalid(_) => 400008,
587            BaseError::AuthorizationStale => 400009,
588            BaseError::AuthorizationVersionInvalid => 400010,
589            BaseError::AuthorizationCheckUnavailable => 400011,
590
591            // ==================== 序列化错误 (5xxxxx) ====================
592            BaseError::JsonSerializeFailed(_) => 500001,
593            BaseError::JsonDeserializeFailed(_) => 500002,
594
595            // ==================== 字段验证错误 (6xxxxx) ====================
596            BaseError::InvalidFieldType(_, _) => 600001,
597            BaseError::InvalidEnumValue(_, _) => 600002,
598            BaseError::StringTooLong(_, _, _) => 600003,
599            BaseError::InvalidJsonFormat(_, _) => 600004,
600            BaseError::ValidationFailed(_, _) => 600005,
601            BaseError::FieldRequired(_) => 600006,
602            BaseError::FieldNotFound(_, _) => 600007,
603            BaseError::FieldPermissionDenied(_, _, _) => 600008,
604
605            // ==================== Action 系统错误 (7xxxxx) ====================
606            BaseError::ActionNotFound(_) => 700001,
607            BaseError::PermissionDenied(_) => 700002,
608            BaseError::Unauthorized(_) => 700003,
609            BaseError::ParamMissing(_) => 700004,
610            BaseError::ParamInvalid(_, _) => 700005,
611            BaseError::RecordNotFound(_) => 700006,
612            BaseError::UserNotFound(_) => 700007,
613            BaseError::InvalidPassword => 700008,
614            BaseError::TableDefinitionNotSet => 700009,
615            #[cfg(feature = "token")]
616            BaseError::StepUpRequired(_) => 700010,
617            BaseError::RateLimitExceeded { .. } => 700011,
618
619            // ==================== 通用错误 (9xxxxx) ====================
620            BaseError::ConfigError(_) => 900001,
621            BaseError::IoError(_) => 900002,
622            BaseError::Unknown(_) => 999999,
623        }
624    }
625
626    /// 返回错误码的 `&'static str` 形式,供 metrics label 使用(零分配、低基数)。
627    ///
628    /// 与 [`BaseError::code`] 一一对应:`code_str()` 是 `code()` 的字符串字面量版本,
629    /// 专用于 `metrics` 的 label(label 必须是 `&'static str`,**严禁** `code().to_string()`
630    /// 造成每次派发堆分配 + 高基数)。新增变体时两者需同步维护,并由
631    /// `test_code_str_matches_code` 守护一致性。
632    pub fn code_str(&self) -> &'static str {
633        match self {
634            // 插件管理错误 (1xxxxx)
635            BaseError::PluginAlreadyRegistered(_) => "100001",
636            BaseError::PluginNotFound(_) => "100002",
637            BaseError::PluginRegisterFailed(_, _) => "100003",
638            BaseError::PluginInitFailed(_, _) => "100004",
639            BaseError::PluginDependencyMissing(_, _) => "100005",
640            BaseError::PluginCircularDependency(_) => "100006",
641            BaseError::PluginConfigInvalid(_, _) => "100007",
642            BaseError::PluginShutdownFailed(_, _) => "100008",
643            BaseError::PluginLifecycleFailed { stage, .. } => match stage {
644                crate::plugin::PluginLifecycleStage::Register => "100003",
645                crate::plugin::PluginLifecycleStage::Initialize => "100004",
646                crate::plugin::PluginLifecycleStage::Shutdown => "100008",
647            },
648            // 数据库错误 (2xxxxx)
649            BaseError::DatabaseConnectionFailed(_) => "200001",
650            BaseError::DatabaseConnectionDbError(_) => "200011",
651            BaseError::DatabaseAlreadyInitialized => "200002",
652            BaseError::DatabaseQueryFailed(_) => "200003",
653            BaseError::DatabaseExecuteFailed(_) => "200004",
654            BaseError::DatabaseInitFailed(_) => "200005",
655            BaseError::DatabaseNotInitialized => "200008",
656            BaseError::DatabaseTransactionFailed(_) => "200009",
657            BaseError::MissingWhereClause(_) => "200010",
658            // Redis 错误 (21xxxx)
659            BaseError::RedisConnectionFailed(_) => "210001",
660            BaseError::RedisAlreadyInitialized => "210002",
661            BaseError::RedisNotInitialized => "210003",
662            BaseError::RedisOperationFailed(_) => "210004",
663            BaseError::RedisOperationDbError(_) => "210011",
664            // HTTP 客户端错误 (3xxxxx)
665            BaseError::HttpClientCreateFailed(_) => "300001",
666            BaseError::HttpRequestFailed(_) => "300002",
667            BaseError::HttpResponseParseFailed(_) => "300003",
668            BaseError::HttpTimeout => "300004",
669            BaseError::HttpClientAlreadyInitialized => "300005",
670            BaseError::HttpClientNotInitialized => "300006",
671            BaseError::HttpCircuitBreakerOpen(_) => "300007",
672            // Token 管理错误 (4xxxxx)
673            BaseError::TokenKeyInvalid(_) => "400001",
674            BaseError::TokenGenerateFailed(_) => "400002",
675            BaseError::TokenVerifyFailed(_) => "400003",
676            BaseError::TokenParseFailed(_) => "400004",
677            BaseError::TokenExpired => "400005",
678            BaseError::TokenTypeInvalid(_) => "400006",
679            BaseError::TokenRevoked => "400007",
680            BaseError::TokenRevocationStateInvalid(_) => "400008",
681            BaseError::AuthorizationStale => "400009",
682            BaseError::AuthorizationVersionInvalid => "400010",
683            BaseError::AuthorizationCheckUnavailable => "400011",
684            // 序列化错误 (5xxxxx)
685            BaseError::JsonSerializeFailed(_) => "500001",
686            BaseError::JsonDeserializeFailed(_) => "500002",
687            // 字段验证错误 (6xxxxx)
688            BaseError::InvalidFieldType(_, _) => "600001",
689            BaseError::InvalidEnumValue(_, _) => "600002",
690            BaseError::StringTooLong(_, _, _) => "600003",
691            BaseError::InvalidJsonFormat(_, _) => "600004",
692            BaseError::ValidationFailed(_, _) => "600005",
693            BaseError::FieldRequired(_) => "600006",
694            BaseError::FieldNotFound(_, _) => "600007",
695            BaseError::FieldPermissionDenied(_, _, _) => "600008",
696            // Action 系统错误 (7xxxxx)
697            BaseError::ActionNotFound(_) => "700001",
698            BaseError::PermissionDenied(_) => "700002",
699            BaseError::Unauthorized(_) => "700003",
700            BaseError::ParamMissing(_) => "700004",
701            BaseError::ParamInvalid(_, _) => "700005",
702            BaseError::RecordNotFound(_) => "700006",
703            BaseError::UserNotFound(_) => "700007",
704            BaseError::InvalidPassword => "700008",
705            BaseError::TableDefinitionNotSet => "700009",
706            #[cfg(feature = "token")]
707            BaseError::StepUpRequired(_) => "700010",
708            BaseError::RateLimitExceeded { .. } => "700011",
709            // 通用错误 (9xxxxx)
710            BaseError::ConfigError(_) => "900001",
711            BaseError::IoError(_) => "900002",
712            BaseError::Unknown(_) => "999999",
713        }
714    }
715
716    /// 引擎级错误分类(弹性重试与任意下游适配的共同基座)。
717    ///
718    /// 返回 [`ErrorCategory`],是 `is_retryable` / `is_client_error` /
719    /// `is_server_error` 的单一事实源。分类语义为**引擎自有**,与具体 HTTP status
720    /// 映射无关——HTTP 映射属调用方传输层边界。
721    ///
722    /// `Transient` 在 `is_server_error` 中视为服务端错误(但可重试),
723    /// 在 `is_client_error` 中**不**视为客户端错误。`Auth` 和 `NotFound` 在
724    /// `is_client_error` 中视为客户端错误(认证/授权失败和资源不存在均归调用方过错)。
725    pub fn category(&self) -> ErrorCategory {
726        use ErrorCategory as C;
727        match self {
728            // 插件管理错误:除注册冲突外均为服务端/配置问题
729            BaseError::PluginAlreadyRegistered(_) => C::Conflict,
730            BaseError::PluginCircularDependency(_) => C::Client,
731            BaseError::PluginDependencyMissing(_, _) => C::Client,
732            BaseError::PluginConfigInvalid(_, _) => C::Client,
733            BaseError::PluginNotFound(_)
734            | BaseError::PluginRegisterFailed(_, _)
735            | BaseError::PluginInitFailed(_, _)
736            | BaseError::PluginShutdownFailed(_, _)
737            | BaseError::PluginLifecycleFailed { .. } => C::Server,
738            // 数据库错误:连接失败/超时/连接池为瞬时(可重试),
739            // 已包装的 DbError 同理(底层连接/超时语义已由 From<DbError> 正确分桶)
740            BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
741                C::Transient
742            }
743            BaseError::MissingWhereClause(_) => C::Client,
744            BaseError::DatabaseAlreadyInitialized
745            | BaseError::DatabaseNotInitialized
746            | BaseError::DatabaseInitFailed(_) => C::Server,
747            // 事务失败可能是死锁(可重试)或约束违反(不可重试),保守归为 Server 避免无限重试
748            BaseError::DatabaseQueryFailed(_)
749            | BaseError::DatabaseExecuteFailed(_)
750            | BaseError::DatabaseTransactionFailed(_) => C::Server,
751            // Redis 错误:连接失败/超时/连接池为瞬时
752            BaseError::RedisConnectionFailed(_) => C::Transient,
753            BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
754            BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
755                match source.category() {
756                    yang_db::DbErrorCategory::Transient => C::Transient,
757                    yang_db::DbErrorCategory::Conflict => C::Conflict,
758                    yang_db::DbErrorCategory::Client => C::Client,
759                    yang_db::DbErrorCategory::NotFound => C::NotFound,
760                    yang_db::DbErrorCategory::Server => C::Server,
761                    _ => C::Server,
762                }
763            }
764            // HTTP 客户端错误
765            BaseError::HttpClientCreateFailed(_)
766            | BaseError::HttpClientNotInitialized
767            | BaseError::HttpClientAlreadyInitialized => C::Client,
768            // 解析失败是客户端编程错误(期望的响应类型不匹配),不是瞬时网络问题
769            BaseError::HttpResponseParseFailed(_) => C::Client,
770            BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
771            // 熔断器打开意味着下游服务不健康,立即重试无济于事
772            BaseError::HttpCircuitBreakerOpen(_) => C::Server,
773            // Token 错误
774            BaseError::TokenKeyInvalid(_)
775            | BaseError::TokenGenerateFailed(_)
776            | BaseError::TokenTypeInvalid(_)
777            | BaseError::TokenParseFailed(_) => C::Client,
778            BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
779                C::Auth
780            }
781            BaseError::TokenRevocationStateInvalid(_) => C::Server,
782            BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
783            BaseError::AuthorizationCheckUnavailable => C::Transient,
784            // 序列化错误
785            BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
786            // 字段验证错误
787            BaseError::InvalidFieldType(_, _)
788            | BaseError::InvalidEnumValue(_, _)
789            | BaseError::StringTooLong(_, _, _)
790            | BaseError::InvalidJsonFormat(_, _)
791            | BaseError::ValidationFailed(_, _)
792            | BaseError::FieldRequired(_)
793            | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
794            BaseError::FieldNotFound(_, _) => C::NotFound,
795            // Action 系统错误
796            BaseError::Unauthorized(_) | BaseError::PermissionDenied(_) => C::Auth,
797            BaseError::ParamMissing(_)
798            | BaseError::ParamInvalid(_, _)
799            | BaseError::RateLimitExceeded { .. } => C::Client,
800            BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
801            BaseError::InvalidPassword => C::Auth,
802            BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
803            #[cfg(feature = "token")]
804            BaseError::StepUpRequired(_) => C::Client,
805            // 通用错误
806            BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
807        }
808    }
809
810    /// 是否为可重试的瞬时错误(等价 `category() == Transient`)。
811    pub fn is_retryable(&self) -> bool {
812        self.category() == ErrorCategory::Transient
813    }
814
815    /// 是否为客户端过错(`Client`、`Auth` 或 `NotFound` 类)。
816    ///
817    /// 用于下游统一适配——客户端过错不可重试,调用方应修正请求而非重试。
818    /// 注意 `Transient` **不**在此列:虽然瞬时错误也可归「服务端」,但它不是
819    /// 调用方过错,且可重试——`is_server_error` 已覆盖该语义。
820    pub fn is_client_error(&self) -> bool {
821        matches!(
822            self.category(),
823            ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
824        )
825    }
826
827    /// 是否为服务端/基础设施错误(`Server`、`Transient` 或 `Conflict`)。
828    ///
829    /// 用于下游统一适配。`Transient` 在此视为服务端(可重试的服务端错误,
830    /// 如连接超时 = HTTP 503 语义);`Conflict` 也计入(资源冲突 = HTTP 409,
831    /// 但常由并发写引起而非纯调用方过错)。
832    pub fn is_server_error(&self) -> bool {
833        matches!(
834            self.category(),
835            ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
836        )
837    }
838}
839
840#[cfg(test)]
841mod tests {
842    use super::*;
843
844    #[test]
845    fn test_error_codes_plugin() {
846        assert_eq!(
847            BaseError::PluginAlreadyRegistered("test".to_string()).code(),
848            100001
849        );
850        assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
851        assert_eq!(
852            BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
853            100003
854        );
855        assert_eq!(
856            BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
857            100004
858        );
859        assert_eq!(
860            BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
861            100005
862        );
863        assert_eq!(
864            BaseError::PluginCircularDependency("test".to_string()).code(),
865            100006
866        );
867        assert_eq!(
868            BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
869            100007
870        );
871        assert_eq!(
872            BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
873            100008
874        );
875    }
876
877    #[test]
878    fn test_error_codes_database() {
879        assert_eq!(
880            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
881                "reason".to_string()
882            ))
883            .code(),
884            200001
885        );
886        assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
887        assert_eq!(
888            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
889                .code(),
890            200003
891        );
892        assert_eq!(
893            BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
894                .code(),
895            200004
896        );
897        assert_eq!(
898            BaseError::DatabaseInitFailed("reason".to_string()).code(),
899            200005
900        );
901        assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
902        assert_eq!(
903            BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
904                "reason".to_string()
905            ))
906            .code(),
907            200009
908        );
909    }
910
911    #[cfg(feature = "http")]
912    #[test]
913    fn test_error_codes_http() {
914        // 注意:reqwest::Error 无法直接构造,通过 code() 方法间接测试
915        assert_eq!(
916            BaseError::HttpResponseParseFailed("reason".to_string()).code(),
917            300003
918        );
919        assert_eq!(BaseError::HttpTimeout.code(), 300004);
920        assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
921        assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
922    }
923
924    #[cfg(feature = "token")]
925    #[test]
926    fn test_error_codes_token() {
927        assert_eq!(
928            BaseError::TokenKeyInvalid("reason".to_string()).code(),
929            400001
930        );
931        assert_eq!(
932            BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
933                jsonwebtoken::errors::ErrorKind::InvalidToken
934            ))
935            .code(),
936            400002
937        );
938        assert_eq!(
939            BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
940                jsonwebtoken::errors::ErrorKind::InvalidToken
941            ))
942            .code(),
943            400003
944        );
945        assert_eq!(
946            BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
947                jsonwebtoken::errors::ErrorKind::InvalidToken
948            ))
949            .code(),
950            400004
951        );
952        assert_eq!(BaseError::TokenExpired.code(), 400005);
953        assert_eq!(
954            BaseError::TokenTypeInvalid("reason".to_string()).code(),
955            400006
956        );
957    }
958
959    #[test]
960    fn test_error_codes_serialization() {
961        assert_eq!(
962            BaseError::JsonSerializeFailed("reason".to_string()).code(),
963            500001
964        );
965        assert_eq!(
966            BaseError::JsonDeserializeFailed("reason".to_string()).code(),
967            500002
968        );
969    }
970
971    #[test]
972    fn test_error_codes_field_validation() {
973        assert_eq!(
974            BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
975            600001
976        );
977        assert_eq!(
978            BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
979            600002
980        );
981        assert_eq!(
982            BaseError::StringTooLong("field".to_string(), 100, 50).code(),
983            600003
984        );
985        assert_eq!(
986            BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
987            600004
988        );
989        assert_eq!(
990            BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
991            600005
992        );
993        assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
994        assert_eq!(
995            BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
996            600007
997        );
998        assert_eq!(
999            BaseError::FieldPermissionDenied(
1000                "table".to_string(),
1001                "field".to_string(),
1002                "reason".to_string()
1003            )
1004            .code(),
1005            600008
1006        );
1007    }
1008
1009    #[test]
1010    fn test_error_codes_action_system() {
1011        assert_eq!(
1012            BaseError::ActionNotFound("test_action".to_string()).code(),
1013            700001
1014        );
1015        assert_eq!(
1016            BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1017            700002
1018        );
1019        assert_eq!(
1020            BaseError::Unauthorized("Token 无效".to_string()).code(),
1021            700003
1022        );
1023        assert_eq!(
1024            BaseError::ParamMissing("user_id".to_string()).code(),
1025            700004
1026        );
1027        assert_eq!(
1028            BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1029            700005
1030        );
1031        assert_eq!(
1032            BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1033            700006
1034        );
1035        assert_eq!(
1036            BaseError::UserNotFound("user_123".to_string()).code(),
1037            700007
1038        );
1039        assert_eq!(BaseError::InvalidPassword.code(), 700008);
1040        assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1041        assert_eq!(
1042            BaseError::RateLimitExceeded {
1043                retry_after_seconds: 30
1044            }
1045            .code(),
1046            700011
1047        );
1048    }
1049
1050    #[test]
1051    fn test_error_codes_general() {
1052        assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1053        assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1054        assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1055    }
1056
1057    #[test]
1058    fn test_all_error_codes_are_nonzero() {
1059        // 确保所有错误码都是非零的
1060        let errors: Vec<BaseError> = vec![
1061            BaseError::PluginNotFound("test".to_string()),
1062            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1063            BaseError::HttpTimeout,
1064            BaseError::TokenExpired,
1065            BaseError::JsonSerializeFailed("test".to_string()),
1066            BaseError::FieldRequired("test".to_string()),
1067            BaseError::ActionNotFound("test".to_string()),
1068            BaseError::PermissionDenied("test".to_string()),
1069            BaseError::Unauthorized("test".to_string()),
1070            BaseError::ParamMissing("test".to_string()),
1071            BaseError::RecordNotFound("test".to_string()),
1072            BaseError::UserNotFound("test".to_string()),
1073            BaseError::InvalidPassword,
1074            BaseError::TableDefinitionNotSet,
1075            BaseError::RateLimitExceeded {
1076                retry_after_seconds: 30,
1077            },
1078            BaseError::Unknown("test".to_string()),
1079        ];
1080
1081        for error in errors {
1082            assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1083        }
1084    }
1085
1086    /// 测试数据库错误链 source() 可遍历
1087    #[test]
1088    fn test_database_error_source_chain() {
1089        use std::error::Error;
1090
1091        let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1092        let base_err = BaseError::DatabaseQueryFailed(db_err);
1093
1094        // BaseError.source() 应返回 Some,指向 DbError
1095        let source = base_err.source();
1096        assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1097    }
1098
1099    /// 测试 From<DbError> 转换保留错误链
1100    #[test]
1101    fn test_from_db_error_preserves_source() {
1102        use std::error::Error;
1103
1104        let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1105        let base_err: BaseError = db_err.into();
1106
1107        // 验证转换后仍可通过 source() 访问底层错误
1108        assert!(base_err.source().is_some());
1109        assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1110    }
1111
1112    #[test]
1113    fn test_redis_connection_and_operation_errors_preserve_db_source() {
1114        use std::error::Error;
1115
1116        let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1117            "connection refused".into(),
1118        ));
1119        let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1120            "WRONGTYPE".into(),
1121        ));
1122
1123        assert_eq!(connection.code(), 210001);
1124        assert_eq!(operation.code(), 210004);
1125        assert!(connection.source().is_some());
1126        assert!(operation.source().is_some());
1127    }
1128
1129    #[test]
1130    fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1131        use std::error::Error;
1132
1133        let error = BaseError::PluginLifecycleFailed {
1134            plugin: "audit".into(),
1135            stage: crate::plugin::PluginLifecycleStage::Shutdown,
1136            source: Box::new(std::io::Error::other("flush failed")),
1137        };
1138
1139        assert_eq!(error.code(), 100008);
1140        assert_eq!(error.code_str(), "100008");
1141        assert!(error.to_string().contains("audit"));
1142        assert!(error.to_string().contains("shutdown"));
1143        assert!(error.source().is_some());
1144    }
1145
1146    /// code_str() 必须与 code() 一致(metrics label 与数值码同源,防漂移)
1147    #[test]
1148    fn test_code_str_matches_code() {
1149        // 覆盖各域代表变体;新增变体时若两处不同步,此处会失败
1150        let samples: Vec<BaseError> = vec![
1151            BaseError::PluginNotFound("p".into()),
1152            BaseError::PluginLifecycleFailed {
1153                plugin: "p".into(),
1154                stage: crate::plugin::PluginLifecycleStage::Initialize,
1155                source: Box::new(std::io::Error::other("init")),
1156            },
1157            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1158            BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1159            BaseError::DatabaseNotInitialized,
1160            BaseError::RedisNotInitialized,
1161            BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1162            BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1163            BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1164            BaseError::HttpTimeout,
1165            BaseError::TokenExpired,
1166            BaseError::TokenRevoked,
1167            BaseError::TokenRevocationStateInvalid("invalid".into()),
1168            BaseError::AuthorizationStale,
1169            BaseError::AuthorizationVersionInvalid,
1170            BaseError::AuthorizationCheckUnavailable,
1171            BaseError::JsonSerializeFailed("s".into()),
1172            BaseError::FieldNotFound("t".into(), "f".into()),
1173            BaseError::ParamInvalid("k".into(), "r".into()),
1174            BaseError::TableDefinitionNotSet,
1175            BaseError::RateLimitExceeded {
1176                retry_after_seconds: 30,
1177            },
1178            BaseError::ConfigError("c".into()),
1179            BaseError::Unknown("u".into()),
1180        ];
1181        for err in samples {
1182            let code = err.code();
1183            let code_str = err.code_str();
1184            assert_eq!(
1185                code_str.parse::<i32>().unwrap(),
1186                code,
1187                "code_str {:?} 与 code {} 不一致(变体 {:?})",
1188                code_str,
1189                code,
1190                err
1191            );
1192        }
1193    }
1194
1195    /// ErrorCategory 全变体覆盖:每个分类至少有一个代表性变体
1196    #[test]
1197    fn test_error_category_coverage() {
1198        // Client
1199        assert_eq!(
1200            BaseError::ParamInvalid("k".into(), "r".into()).category(),
1201            ErrorCategory::Client
1202        );
1203        assert_eq!(
1204            BaseError::ValidationFailed("f".into(), "r".into()).category(),
1205            ErrorCategory::Client
1206        );
1207        // Auth
1208        assert_eq!(
1209            BaseError::Unauthorized("u".into()).category(),
1210            ErrorCategory::Auth
1211        );
1212        assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1213        assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1214        // NotFound
1215        assert_eq!(
1216            BaseError::RecordNotFound("r".into()).category(),
1217            ErrorCategory::NotFound
1218        );
1219        assert_eq!(
1220            BaseError::FieldNotFound("t".into(), "f".into()).category(),
1221            ErrorCategory::NotFound
1222        );
1223        // Conflict
1224        assert_eq!(
1225            BaseError::PluginAlreadyRegistered("p".into()).category(),
1226            ErrorCategory::Conflict
1227        );
1228        // Transient
1229        assert_eq!(
1230            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1231                .category(),
1232            ErrorCategory::Transient
1233        );
1234        assert_eq!(
1235            BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1236                .category(),
1237            ErrorCategory::Transient
1238        );
1239        assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1240        // Server
1241        assert_eq!(
1242            BaseError::Unknown("u".into()).category(),
1243            ErrorCategory::Server
1244        );
1245        assert_eq!(
1246            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1247            ErrorCategory::Server
1248        );
1249    }
1250
1251    /// is_retryable = (category == Transient)
1252    #[test]
1253    fn test_is_retryable() {
1254        assert!(
1255            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1256                .is_retryable()
1257        );
1258        assert!(BaseError::HttpTimeout.is_retryable());
1259        assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1260        assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1261        assert!(!BaseError::Unknown("u".into()).is_retryable());
1262    }
1263
1264    /// is_client_error = (Client | Auth | NotFound)
1265    #[test]
1266    fn test_is_client_error() {
1267        assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1268        assert!(BaseError::Unauthorized("u".into()).is_client_error());
1269        assert!(BaseError::TokenExpired.is_client_error());
1270        assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1271        assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1272        assert!(
1273            !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1274                .is_client_error()
1275        );
1276        assert!(!BaseError::Unknown("u".into()).is_client_error());
1277    }
1278
1279    /// is_server_error = (Server | Transient | Conflict)
1280    #[test]
1281    fn test_is_server_error() {
1282        assert!(BaseError::Unknown("u".into()).is_server_error());
1283        assert!(
1284            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1285                .is_server_error()
1286        );
1287        assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1288        assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1289        assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1290    }
1291}