Skip to main content

yang_base/error/
mod.rs

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