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