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