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    /// 当前后端/构建不支持请求的能力(如方言专属语法)。
120    ///
121    /// 与 [`BaseError::ConfigError`] 区分:这是「运行时能力矩阵」的显式拒绝,
122    /// 调用方应降级或换用受支持的入口,而不是修复配置。
123    #[error("当前后端不支持该能力: {0}")]
124    UnsupportedCapability(String),
125
126    /// 表与事务不属于同一逻辑数据源。
127    #[error("事务与表数据源不一致 [{table}]: 期望 {expected},实际 {actual}")]
128    DatasourceMismatch {
129        /// 表名。
130        table: String,
131        /// 表所属数据源。
132        expected: String,
133        /// 事务所属数据源(未标注时为 `unscoped`)。
134        actual: String,
135    },
136
137    /// UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作
138    ///
139    /// 与 yang-db 的 `MissingWhereClause` 安全网对齐:无 WHERE 的更新/删除
140    /// 始终被拒绝,以防止误操作整表。
141    #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
142    MissingWhereClause(String),
143
144    // ==================== Redis 错误 ====================
145    /// Redis 连接失败,持有底层 DbError 以保留错误链。
146    #[error("Redis 连接失败: {0}")]
147    RedisConnectionFailed(#[source] yang_db::DbError),
148
149    /// Redis 已初始化
150    #[error("Redis 已初始化")]
151    RedisAlreadyInitialized,
152
153    /// Redis 未初始化
154    #[error("Redis 未初始化")]
155    RedisNotInitialized,
156
157    /// Redis 操作失败,持有底层 DbError 以保留错误链。
158    #[error("Redis 操作失败: {0}")]
159    RedisOperationFailed(#[source] yang_db::DbError),
160
161    /// Redis 操作失败,持有底层 DbError 以保留错误链
162    #[error("Redis 操作失败: {0}")]
163    RedisOperationDbError(#[source] yang_db::DbError),
164
165    // ==================== HTTP 客户端错误 ====================
166    /// HTTP 客户端创建失败,持有底层 reqwest::Error 以保留错误链
167    #[cfg(feature = "http")]
168    #[error("HTTP 客户端创建失败: {0}")]
169    HttpClientCreateFailed(#[source] reqwest::Error),
170
171    /// HTTP 客户端创建失败(无 http feature 时使用字符串)
172    #[cfg(not(feature = "http"))]
173    #[error("HTTP 客户端创建失败: {0}")]
174    HttpClientCreateFailed(String),
175
176    /// HTTP 请求失败,持有底层 reqwest::Error 以保留错误链
177    #[cfg(feature = "http")]
178    #[error("HTTP 请求失败: {0}")]
179    HttpRequestFailed(#[source] reqwest::Error),
180
181    /// HTTP 请求失败(无 http feature 时使用字符串)
182    #[cfg(not(feature = "http"))]
183    #[error("HTTP 请求失败: {0}")]
184    HttpRequestFailed(String),
185
186    /// HTTP 响应解析失败
187    #[error("HTTP 响应解析失败: {0}")]
188    HttpResponseParseFailed(String),
189
190    /// HTTP 响应体超过配置上限(防异常/恶意上游耗尽内存)
191    #[error("HTTP 响应体超过上限: 上限 {limit} 字节, 实际 {actual:?} 字节")]
192    HttpResponseTooLarge {
193        /// 配置的响应体上限(字节)。
194        limit: usize,
195        /// 上游声明(Content-Length)的实际大小;流式累计触发时为 None。
196        actual: Option<u64>,
197    },
198
199    /// HTTP 超时
200    #[error("HTTP 请求超时")]
201    HttpTimeout,
202
203    /// HTTP 客户端已初始化
204    #[error("HTTP 客户端已初始化")]
205    HttpClientAlreadyInitialized,
206
207    /// HTTP 客户端未初始化
208    #[error("HTTP 客户端未初始化")]
209    HttpClientNotInitialized,
210
211    /// HTTP 熔断器打开:目标 host 近期连续失败,请求被快速拒绝
212    #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
213    HttpCircuitBreakerOpen(String),
214
215    /// 上游依赖暂时不可用(**与具体传输无关**)。
216    ///
217    /// 存在的理由:[`BaseError::HttpRequestFailed`] 在 `http` feature 开启时持有
218    /// `reqwest::Error`、关闭时持有 `String`,也就是说**它的可构造性取决于 feature**。
219    /// 非 HTTP 传输(SMTP、消息队列等)需要同一语义的可重试错误,却又不能依赖该
220    /// feature —— 否则「上游暂时不可用」会随构建配置在「可重试」与「不可重试」之间
221    /// 漂移(历史上邮件投递就因此从 503 退化成 500)。
222    ///
223    /// 分类是 [`ErrorCategory::Transient`],在 HTTP 边界映射为 **503**,
224    /// 语义上等同于 `HttpRequestFailed`,但不携带传输层错误链。
225    #[error("上游服务暂不可用: {0}")]
226    UpstreamUnavailable(String),
227
228    // ==================== Token 管理错误 ====================
229    /// Token 密钥无效
230    #[error("Token 密钥无效: {0}")]
231    TokenKeyInvalid(String),
232
233    /// Token 生成失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
234    #[cfg(feature = "token")]
235    #[error("Token 生成失败: {0}")]
236    TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
237
238    /// Token 生成失败(无 token feature 时使用字符串)
239    #[cfg(not(feature = "token"))]
240    #[error("Token 生成失败: {0}")]
241    TokenGenerateFailed(String),
242
243    /// Token 验证失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
244    #[cfg(feature = "token")]
245    #[error("Token 验证失败: {0}")]
246    TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
247
248    /// Token 验证失败(无 token feature 时使用字符串)
249    #[cfg(not(feature = "token"))]
250    #[error("Token 验证失败: {0}")]
251    TokenVerifyFailed(String),
252
253    /// Token 解析失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
254    #[cfg(feature = "token")]
255    #[error("Token 解析失败: {0}")]
256    TokenParseFailed(#[source] jsonwebtoken::errors::Error),
257
258    /// Token 解析失败(无 token feature 时使用字符串)
259    #[cfg(not(feature = "token"))]
260    #[error("Token 解析失败: {0}")]
261    TokenParseFailed(String),
262
263    /// Token 已过期
264    #[error("Token 已过期")]
265    TokenExpired,
266
267    /// Token 已被撤销(命中黑名单)
268    #[error("Token 已被撤销")]
269    TokenRevoked,
270
271    /// Token 撤销状态损坏或返回结构不符合协议。
272    #[error("Token 撤销状态无效: {0}")]
273    TokenRevocationStateInvalid(String),
274
275    /// Access Token 中的授权版本已落后于当前事实版本。
276    #[error("授权状态已变更,请刷新登录")]
277    AuthorizationStale,
278
279    /// Access Token 中的授权版本缺失、非法或领先于事实版本。
280    #[error("授权版本无效")]
281    AuthorizationVersionInvalid,
282
283    /// 授权版本缓存与事实存储均无法完成请求时校验。
284    #[error("授权状态暂时无法校验")]
285    AuthorizationCheckUnavailable,
286
287    /// Token 类型无效
288    #[error("Token 类型无效: {0}")]
289    TokenTypeInvalid(String),
290
291    // ==================== 序列化错误 ====================
292    /// JSON 序列化失败
293    #[error("JSON 序列化失败: {0}")]
294    JsonSerializeFailed(String),
295
296    /// JSON 反序列化失败
297    #[error("JSON 反序列化失败: {0}")]
298    JsonDeserializeFailed(String),
299
300    // ==================== 字段验证错误 ====================
301    /// 字段类型无效
302    #[error("字段类型无效 [{0}]: {1}")]
303    InvalidFieldType(String, String),
304
305    /// 枚举值无效
306    #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
307    InvalidEnumValue(String, String),
308
309    /// 字符串长度超出限制
310    #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
311    StringTooLong(String, usize, usize),
312
313    /// JSON 格式无效
314    #[error("JSON 格式无效 [{0}]: {1}")]
315    InvalidJsonFormat(String, String),
316
317    /// 验证失败
318    #[error("验证失败 [{0}]: {1}")]
319    ValidationFailed(String, String),
320
321    /// 字段必填
322    #[error("字段必填: {0}")]
323    FieldRequired(String),
324
325    /// 字段未找到
326    #[error("字段未找到 [表: {0}]: {1}")]
327    FieldNotFound(String, String),
328
329    /// 字段权限被拒绝
330    #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
331    FieldPermissionDenied(String, String, String),
332
333    // ==================== Action 系统错误 ====================
334    /// Action 未找到
335    #[error("Action 未找到: {0}")]
336    ActionNotFound(String),
337
338    /// 权限被拒绝
339    #[error("权限被拒绝: {0}")]
340    PermissionDenied(String),
341
342    /// 未授权
343    #[error("未授权: {0}")]
344    Unauthorized(String),
345
346    /// 参数缺失
347    #[error("参数缺失: {0}")]
348    ParamMissing(String),
349
350    /// 参数无效
351    #[error("参数无效 [{0}]: {1}")]
352    ParamInvalid(String, String),
353
354    /// 请求超过速率限制。
355    #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
356    RateLimitExceeded {
357        /// 建议客户端等待的秒数。
358        retry_after_seconds: u64,
359    },
360
361    /// 第一因子已通过,需要第二因子(TOTP 动态码或恢复码)才能完成认证。
362    ///
363    /// 仅在密码校验通过后返回:客户端据此进入第二因子输入阶段
364    /// (两段式登录:账号密码 → 动态码),与 `InvalidPassword` 语义区分。
365    #[error("需要输入双重验证码")]
366    SecondFactorRequired,
367
368    /// 记录未找到
369    #[error("记录未找到: {0}")]
370    RecordNotFound(String),
371
372    /// 用户未找到
373    #[error("用户未找到: {0}")]
374    UserNotFound(String),
375
376    /// 密码无效
377    #[error("密码无效")]
378    InvalidPassword,
379
380    /// 表定义未设置
381    #[error("表定义未设置")]
382    TableDefinitionNotSet,
383
384    /// 敏感 Action 尚未完成短期重认证。
385    #[cfg(feature = "token")]
386    #[error("敏感操作需要重新认证")]
387    StepUpRequired(crate::action::StepUpChallenge),
388
389    // ==================== 通用错误 ====================
390    /// 配置错误
391    #[error("配置错误: {0}")]
392    ConfigError(String),
393
394    /// IO 错误
395    #[error("IO 错误: {0}")]
396    IoError(String),
397
398    /// 未知错误
399    #[error("未知错误: {0}")]
400    Unknown(String),
401}
402
403// ==================== From trait 实现 ====================
404
405/// 从数据库约束错误的报文里提取**唯一键冲突**的键名。
406///
407/// 返回 `None` 表示「这不是唯一键冲突」。
408///
409/// # 为什么不看错误码
410///
411/// MySQL 的外键、非空、CHECK 与唯一键**共用同一个 SQLSTATE(23000)**,
412/// PostgreSQL 的唯一约束是 23505 而 SQLSTATE 在 `yang-db` 里已被抹平成
413/// `DbError::ConstraintError`。所以在这一层只能看报文。
414///
415/// 覆盖两种形态:
416/// - MySQL:`Duplicate entry 'x' for key 'source_key'`(键名可能被库名/表名限定)
417/// - PostgreSQL:`duplicate key value violates unique constraint "xxx"`
418fn duplicate_key_field(message: &str) -> Option<String> {
419    if message.contains("Duplicate entry") {
420        if let Some((_, rest)) = message.split_once("for key '") {
421            // MySQL 8 会写成 `库.表.键`,取最后一段才是键名本身
422            let raw = rest.split('\'').next().unwrap_or_default();
423            let last = raw.rsplit('.').next().unwrap_or(raw);
424            if !last.is_empty() {
425                return Some(last.to_string());
426            }
427        }
428    }
429    if message.contains("duplicate key value violates unique constraint") {
430        if let Some((_, rest)) = message.split_once("unique constraint \"") {
431            let name = rest.split('"').next().unwrap_or_default();
432            if !name.is_empty() {
433                return Some(name.to_string());
434            }
435        }
436    }
437    None
438}
439
440/// 从 yang_db::DbError 转换为 BaseError
441///
442/// 按 DbError 变体分类映射到对应的 BaseError 变体:
443/// - 查询类 → DatabaseQueryFailed
444/// - 执行类 → DatabaseExecuteFailed(**唯一键冲突例外**,见下)
445/// - 事务类 → DatabaseTransactionFailed
446/// - 连接类 → DatabaseConnectionFailed(包装 DbError 保留错误链)
447/// - Redis 连接类 → RedisConnectionFailed
448/// - Redis 其他操作类 → RedisOperationFailed
449///
450/// 唯一键冲突映射为 [`BaseError::ParamInvalid`]:它是**可归因的输入问题**
451/// (自动派生的 `source_key`、系统生成的 token 都可能撞唯一索引),
452/// 落成 `DatabaseExecuteFailed` 会让控制台只能显示「数据库执行失败」,
453/// 运维看不出撞的是哪个键。
454#[allow(unreachable_patterns)]
455impl From<yang_db::DbError> for BaseError {
456    fn from(err: yang_db::DbError) -> Self {
457        use yang_db::DbError as D;
458        match &err {
459            // 查询类:查询错误、表不存在、类型转换、反序列化、不支持的操作符、未知错误
460            D::QueryError(_)
461            | D::TableNotFound(_)
462            | D::TypeConversionError(_)
463            | D::DeserializationError(_)
464            | D::UnsupportedOperator(_)
465            | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
466
467            // 结构化 SQLSTATE:唯一键冲突归因为参数错误;连接类保留错误链;
468            // 其余约束/语法/数据错误统一落到执行失败,避免把数据完整性问题
469            // 误报成用户输入错误。
470            D::DatabaseError(info) => match info.kind() {
471                yang_db::SqlErrorKind::UniqueViolation => {
472                    let field = info
473                        .constraint()
474                        .and_then(|constraint| constraint.rsplit('.').next())
475                        .map(str::to_string)
476                        .or_else(|| duplicate_key_field(info.message()))
477                        .unwrap_or_else(|| "unknown".to_string());
478                    BaseError::ParamInvalid(field, "该值已存在".to_string())
479                }
480                yang_db::SqlErrorKind::UndefinedTable => BaseError::DatabaseQueryFailed(err),
481                yang_db::SqlErrorKind::ConnectionFailure
482                | yang_db::SqlErrorKind::TooManyConnections => {
483                    BaseError::DatabaseConnectionDbError(err)
484                }
485                _ => BaseError::DatabaseExecuteFailed(err),
486            },
487
488            // 连接池关闭不可重试,保留错误链供运维定位。
489            D::PoolClosed => BaseError::DatabaseConnectionDbError(err),
490
491            // 唯一键冲突:**先于**通用执行类分支判定,让它变成可归因的参数错误。
492            // 报文不匹配时原样落回 DatabaseExecuteFailed——外键/非空/CHECK 都走这一支。
493            D::ConstraintError(message) => match duplicate_key_field(message) {
494                Some(field) => BaseError::ParamInvalid(field, "该值已存在".to_string()),
495                None => BaseError::DatabaseExecuteFailed(err),
496            },
497
498            // 其余执行类:SQL 语法错误、缺少 WHERE 条件、缺少 GROUP BY、序列化错误、参数非法
499            D::SqlSyntaxError(_)
500            | D::MissingWhereClause
501            | D::MissingGroupByClause
502            | D::InvalidArgument(_)
503            | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
504
505            // 事务类:事务错误
506            D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
507
508            // 连接类:连接错误(保留底层 DbError 错误链)→ DatabaseConnectionDbError (200011)
509            D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
510
511            // Redis 连接类:保留底层 DbError 错误链
512            D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
513
514            // Redis 操作类:保留底层 DbError 错误链
515            D::RedisCommandError(_)
516            | D::RedisPoolError(_)
517            | D::RedisPoolClosed
518            | D::RedisError(_)
519            | D::RedisTypeConversionError(_)
520            | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
521
522            // 未来新增变体(DbError 标注 #[non_exhaustive])统一按查询失败处理
523            _ => BaseError::DatabaseQueryFailed(err),
524        }
525    }
526}
527
528/// 从 std::io::Error 转换为 BaseError
529impl From<std::io::Error> for BaseError {
530    fn from(err: std::io::Error) -> Self {
531        BaseError::IoError(err.to_string())
532    }
533}
534
535/// 从 serde_json::Error 转换为 BaseError
536impl From<serde_json::Error> for BaseError {
537    fn from(err: serde_json::Error) -> Self {
538        if err.is_syntax() || err.is_data() || err.is_eof() {
539            BaseError::JsonDeserializeFailed(err.to_string())
540        } else {
541            BaseError::JsonSerializeFailed(err.to_string())
542        }
543    }
544}
545
546/// 从 reqwest::Error 转换为 BaseError
547#[cfg(feature = "http")]
548impl From<reqwest::Error> for BaseError {
549    fn from(err: reqwest::Error) -> Self {
550        if err.is_timeout() {
551            BaseError::HttpTimeout
552        } else {
553            // is_connect() 属于「发送请求」阶段的连接失败(DNS/TCP/TLS),
554            // 客户端此时早已创建成功,故与其它发送错误统一归为 HttpRequestFailed。
555            // 真正的客户端创建失败由 http/client.rs 显式 map_err(HttpClientCreateFailed) 处理。
556            BaseError::HttpRequestFailed(err)
557        }
558    }
559}
560
561/// 从 jsonwebtoken::errors::Error 转换为 BaseError
562///
563/// 按 ErrorKind 分类映射:
564/// - ExpiredSignature → TokenExpired
565/// - InvalidToken / InvalidSignature → TokenVerifyFailed
566/// - 其他 → TokenParseFailed
567#[cfg(feature = "token")]
568impl From<jsonwebtoken::errors::Error> for BaseError {
569    fn from(err: jsonwebtoken::errors::Error) -> Self {
570        use jsonwebtoken::errors::ErrorKind;
571        match err.kind() {
572            ErrorKind::ExpiredSignature => BaseError::TokenExpired,
573            ErrorKind::InvalidToken
574            | ErrorKind::InvalidSignature
575            | ErrorKind::InvalidIssuer
576            | ErrorKind::InvalidAudience
577            | ErrorKind::InvalidSubject
578            | ErrorKind::InvalidAlgorithm
579            | ErrorKind::MissingAlgorithm
580            | ErrorKind::ImmatureSignature
581            | ErrorKind::MissingRequiredClaim(_)
582            | ErrorKind::InvalidEcdsaKey
583            | ErrorKind::InvalidRsaKey(_)
584            | ErrorKind::InvalidKeyFormat
585            | ErrorKind::RsaFailedSigning
586            | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
587            // 真正解析/IO 错误 → TokenParseFailed
588            ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
589                BaseError::TokenParseFailed(err)
590            }
591            // 防非穷尽: 未显式列出的验证类错误 → TokenVerifyFailed
592            _ => BaseError::TokenVerifyFailed(err),
593        }
594    }
595}
596
597/// 引擎级错误分类(与具体 HTTP/传输层无关)。
598///
599/// 用于下游统一适配(弹性重试、错误上报分桶、HTTP status 映射的中间层)。
600/// HTTP status 映射属调用方传输层边界,不在引擎层硬编码。
601///
602/// `is_client_error()` = `Client` + `Auth` + `NotFound`;`is_server_error()` = `Server` +
603/// `Transient` + `Conflict`。详见 [`BaseError::category`] 文档。
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605#[non_exhaustive]
606pub enum ErrorCategory {
607    /// 调用方过错(参数错误、字段验证、序列化、插件依赖/配置/循环)
608    Client,
609    /// 认证/授权失败(登录过期、Token 撤销、密码错误、权限不足)
610    Auth,
611    /// 资源不存在(记录/用户/Action/表未找到)
612    NotFound,
613    /// 资源冲突(插件注册冲突)
614    Conflict,
615    /// 瞬时故障(连接失败/超时/连接池/HTTP 超时/熔断打开),可重试
616    ///
617    /// 在 `is_server_error` 中视为服务端错误(可重试的服务端故障,
618    /// 如连接超时 = HTTP 503 语义),但 `is_client_error` 中**不**视为客户端错误。
619    Transient,
620    /// 服务端/基础设施错误(内部失败、配置错误、未知错误)
621    Server,
622}
623
624/// 服务尚未就绪:传输层 `/health/ready` 与管理面就绪探针共用的错误码。
625///
626/// 取值沿用 `900001`(通用错误区间)以保持既有线格式不变;两处引用同一常量,
627/// 禁止再各自硬编码字面量。见 `test_not_ready_code_is_stable`。
628pub const NOT_READY_CODE: i32 = 900001;
629
630impl BaseError {
631    /// 获取错误码
632    ///
633    /// 返回与错误类型对应的数字错误码,用于 API 响应
634    ///
635    /// # 错误码规范
636    ///
637    /// - 1xxxxx: 插件管理错误
638    /// - 2xxxxx: 数据库错误
639    ///   - 21xxxx: Redis 错误(隶属数据库 2xxxxx 大类)
640    /// - 3xxxxx: HTTP 客户端错误
641    /// - 4xxxxx: Token 管理错误
642    /// - 5xxxxx: 序列化错误
643    /// - 6xxxxx: 字段验证错误
644    /// - 7xxxxx: Action 系统错误
645    /// - 9xxxxx: 通用错误
646    ///
647    /// # 返回
648    ///
649    /// - 错误码(非零整数)
650    ///
651    /// # 示例
652    ///
653    /// ```rust,ignore
654    /// use yang_base::error::BaseError;
655    ///
656    /// let error = BaseError::FieldRequired("username".to_string());
657    /// assert_eq!(error.code(), 600006);
658    /// ```
659    pub fn code(&self) -> i32 {
660        match self {
661            // ==================== 插件管理错误 (1xxxxx) ====================
662            BaseError::PluginAlreadyRegistered(_) => 100001,
663            BaseError::PluginNotFound(_) => 100002,
664            BaseError::PluginRegisterFailed(_, _) => 100003,
665            BaseError::PluginInitFailed(_, _) => 100004,
666            BaseError::PluginDependencyMissing(_, _) => 100005,
667            BaseError::PluginCircularDependency(_) => 100006,
668            BaseError::PluginConfigInvalid(_, _) => 100007,
669            BaseError::PluginShutdownFailed(_, _) => 100008,
670            BaseError::PluginLifecycleFailed { stage, .. } => match stage {
671                crate::plugin::PluginLifecycleStage::Register => 100003,
672                crate::plugin::PluginLifecycleStage::Initialize => 100004,
673                crate::plugin::PluginLifecycleStage::Shutdown => 100008,
674            },
675
676            // ==================== 数据库错误 (2xxxxx) ====================
677            BaseError::DatabaseConnectionFailed(_) => 200001,
678            BaseError::DatabaseConnectionDbError(_) => 200011,
679            BaseError::DatabaseAlreadyInitialized => 200002,
680            BaseError::DatabaseQueryFailed(_) => 200003,
681            BaseError::DatabaseExecuteFailed(_) => 200004,
682            BaseError::DatabaseInitFailed(_) => 200005,
683            BaseError::DatabaseNotInitialized => 200008,
684            BaseError::DatabaseTransactionFailed(_) => 200009,
685            BaseError::MissingWhereClause(_) => 200010,
686            BaseError::UnsupportedCapability(_) => 200012,
687            BaseError::DatasourceMismatch { .. } => 200013,
688
689            // ==================== Redis 错误 (21xxxx) ====================
690            BaseError::RedisConnectionFailed(_) => 210001,
691            BaseError::RedisAlreadyInitialized => 210002,
692            BaseError::RedisNotInitialized => 210003,
693            BaseError::RedisOperationFailed(_) => 210004,
694            BaseError::RedisOperationDbError(_) => 210011,
695
696            // ==================== HTTP 客户端错误 (3xxxxx) ====================
697            BaseError::HttpClientCreateFailed(_) => 300001,
698            BaseError::HttpRequestFailed(_) => 300002,
699            BaseError::HttpResponseParseFailed(_) => 300003,
700            BaseError::HttpTimeout => 300004,
701            BaseError::HttpClientAlreadyInitialized => 300005,
702            BaseError::HttpClientNotInitialized => 300006,
703            BaseError::HttpCircuitBreakerOpen(_) => 300007,
704            BaseError::HttpResponseTooLarge { .. } => 300008,
705            // 与传输无关的上游依赖错误:与 300002 同为 Transient,但可在任何
706            // feature 组合下构造(见变体文档)。
707            BaseError::UpstreamUnavailable(_) => 300009,
708
709            // ==================== Token 管理错误 (4xxxxx) ====================
710            BaseError::TokenKeyInvalid(_) => 400001,
711            BaseError::TokenGenerateFailed(_) => 400002,
712            BaseError::TokenVerifyFailed(_) => 400003,
713            BaseError::TokenParseFailed(_) => 400004,
714            BaseError::TokenExpired => 400005,
715            BaseError::TokenTypeInvalid(_) => 400006,
716            BaseError::TokenRevoked => 400007,
717            BaseError::TokenRevocationStateInvalid(_) => 400008,
718            BaseError::AuthorizationStale => 400009,
719            BaseError::AuthorizationVersionInvalid => 400010,
720            BaseError::AuthorizationCheckUnavailable => 400011,
721
722            // ==================== 序列化错误 (5xxxxx) ====================
723            BaseError::JsonSerializeFailed(_) => 500001,
724            BaseError::JsonDeserializeFailed(_) => 500002,
725
726            // ==================== 字段验证错误 (6xxxxx) ====================
727            BaseError::InvalidFieldType(_, _) => 600001,
728            BaseError::InvalidEnumValue(_, _) => 600002,
729            BaseError::StringTooLong(_, _, _) => 600003,
730            BaseError::InvalidJsonFormat(_, _) => 600004,
731            BaseError::ValidationFailed(_, _) => 600005,
732            BaseError::FieldRequired(_) => 600006,
733            BaseError::FieldNotFound(_, _) => 600007,
734            BaseError::FieldPermissionDenied(_, _, _) => 600008,
735
736            // ==================== Action 系统错误 (7xxxxx) ====================
737            BaseError::ActionNotFound(_) => 700001,
738            BaseError::PermissionDenied(_) => 700002,
739            BaseError::Unauthorized(_) => 700003,
740            BaseError::ParamMissing(_) => 700004,
741            BaseError::ParamInvalid(_, _) => 700005,
742            BaseError::RecordNotFound(_) => 700006,
743            BaseError::UserNotFound(_) => 700007,
744            BaseError::InvalidPassword => 700008,
745            BaseError::TableDefinitionNotSet => 700009,
746            #[cfg(feature = "token")]
747            BaseError::StepUpRequired(_) => 700010,
748            BaseError::RateLimitExceeded { .. } => 700011,
749            BaseError::SecondFactorRequired => 700012,
750
751            // ==================== 通用错误 (9xxxxx) ====================
752            BaseError::ConfigError(_) => 900001,
753            BaseError::IoError(_) => 900002,
754            BaseError::Unknown(_) => 999999,
755        }
756    }
757
758    /// 返回错误码的 `&'static str` 形式,供 metrics label 使用(零分配、低基数)。
759    ///
760    /// 与 [`BaseError::code`] 一一对应:`code_str()` 是 `code()` 的字符串字面量版本,
761    /// 专用于 `metrics` 的 label(label 必须是 `&'static str`,**严禁** `code().to_string()`
762    /// 造成每次派发堆分配 + 高基数)。新增变体时两者需同步维护,并由
763    /// `test_code_str_matches_code` 守护一致性。
764    pub fn code_str(&self) -> &'static str {
765        match self {
766            // 插件管理错误 (1xxxxx)
767            BaseError::PluginAlreadyRegistered(_) => "100001",
768            BaseError::PluginNotFound(_) => "100002",
769            BaseError::PluginRegisterFailed(_, _) => "100003",
770            BaseError::PluginInitFailed(_, _) => "100004",
771            BaseError::PluginDependencyMissing(_, _) => "100005",
772            BaseError::PluginCircularDependency(_) => "100006",
773            BaseError::PluginConfigInvalid(_, _) => "100007",
774            BaseError::PluginShutdownFailed(_, _) => "100008",
775            BaseError::PluginLifecycleFailed { stage, .. } => match stage {
776                crate::plugin::PluginLifecycleStage::Register => "100003",
777                crate::plugin::PluginLifecycleStage::Initialize => "100004",
778                crate::plugin::PluginLifecycleStage::Shutdown => "100008",
779            },
780            // 数据库错误 (2xxxxx)
781            BaseError::DatabaseConnectionFailed(_) => "200001",
782            BaseError::DatabaseConnectionDbError(_) => "200011",
783            BaseError::DatabaseAlreadyInitialized => "200002",
784            BaseError::DatabaseQueryFailed(_) => "200003",
785            BaseError::DatabaseExecuteFailed(_) => "200004",
786            BaseError::DatabaseInitFailed(_) => "200005",
787            BaseError::DatabaseNotInitialized => "200008",
788            BaseError::DatabaseTransactionFailed(_) => "200009",
789            BaseError::MissingWhereClause(_) => "200010",
790            BaseError::UnsupportedCapability(_) => "200012",
791            BaseError::DatasourceMismatch { .. } => "200013",
792            // Redis 错误 (21xxxx)
793            BaseError::RedisConnectionFailed(_) => "210001",
794            BaseError::RedisAlreadyInitialized => "210002",
795            BaseError::RedisNotInitialized => "210003",
796            BaseError::RedisOperationFailed(_) => "210004",
797            BaseError::RedisOperationDbError(_) => "210011",
798            // HTTP 客户端错误 (3xxxxx)
799            BaseError::HttpClientCreateFailed(_) => "300001",
800            BaseError::HttpRequestFailed(_) => "300002",
801            BaseError::HttpResponseParseFailed(_) => "300003",
802            BaseError::HttpTimeout => "300004",
803            BaseError::HttpClientAlreadyInitialized => "300005",
804            BaseError::HttpClientNotInitialized => "300006",
805            BaseError::HttpCircuitBreakerOpen(_) => "300007",
806            BaseError::HttpResponseTooLarge { .. } => "300008",
807            BaseError::UpstreamUnavailable(_) => "300009",
808            // Token 管理错误 (4xxxxx)
809            BaseError::TokenKeyInvalid(_) => "400001",
810            BaseError::TokenGenerateFailed(_) => "400002",
811            BaseError::TokenVerifyFailed(_) => "400003",
812            BaseError::TokenParseFailed(_) => "400004",
813            BaseError::TokenExpired => "400005",
814            BaseError::TokenTypeInvalid(_) => "400006",
815            BaseError::TokenRevoked => "400007",
816            BaseError::TokenRevocationStateInvalid(_) => "400008",
817            BaseError::AuthorizationStale => "400009",
818            BaseError::AuthorizationVersionInvalid => "400010",
819            BaseError::AuthorizationCheckUnavailable => "400011",
820            // 序列化错误 (5xxxxx)
821            BaseError::JsonSerializeFailed(_) => "500001",
822            BaseError::JsonDeserializeFailed(_) => "500002",
823            // 字段验证错误 (6xxxxx)
824            BaseError::InvalidFieldType(_, _) => "600001",
825            BaseError::InvalidEnumValue(_, _) => "600002",
826            BaseError::StringTooLong(_, _, _) => "600003",
827            BaseError::InvalidJsonFormat(_, _) => "600004",
828            BaseError::ValidationFailed(_, _) => "600005",
829            BaseError::FieldRequired(_) => "600006",
830            BaseError::FieldNotFound(_, _) => "600007",
831            BaseError::FieldPermissionDenied(_, _, _) => "600008",
832            // Action 系统错误 (7xxxxx)
833            BaseError::ActionNotFound(_) => "700001",
834            BaseError::PermissionDenied(_) => "700002",
835            BaseError::Unauthorized(_) => "700003",
836            BaseError::ParamMissing(_) => "700004",
837            BaseError::ParamInvalid(_, _) => "700005",
838            BaseError::RecordNotFound(_) => "700006",
839            BaseError::UserNotFound(_) => "700007",
840            BaseError::InvalidPassword => "700008",
841            BaseError::TableDefinitionNotSet => "700009",
842            #[cfg(feature = "token")]
843            BaseError::StepUpRequired(_) => "700010",
844            BaseError::RateLimitExceeded { .. } => "700011",
845            BaseError::SecondFactorRequired => "700012",
846            // 通用错误 (9xxxxx)
847            BaseError::ConfigError(_) => "900001",
848            BaseError::IoError(_) => "900002",
849            BaseError::Unknown(_) => "999999",
850        }
851    }
852
853    /// 引擎级错误分类(弹性重试与任意下游适配的共同基座)。
854    ///
855    /// 返回 [`ErrorCategory`],是 `is_retryable` / `is_client_error` /
856    /// `is_server_error` 的单一事实源。分类语义为**引擎自有**,与具体 HTTP status
857    /// 映射无关——HTTP 映射属调用方传输层边界。
858    ///
859    /// `Transient` 在 `is_server_error` 中视为服务端错误(但可重试),
860    /// 在 `is_client_error` 中**不**视为客户端错误。`Auth` 和 `NotFound` 在
861    /// `is_client_error` 中视为客户端错误(认证/授权失败和资源不存在均归调用方过错)。
862    pub fn category(&self) -> ErrorCategory {
863        use ErrorCategory as C;
864        match self {
865            // 插件管理错误:除注册冲突外均为服务端/配置问题
866            BaseError::PluginAlreadyRegistered(_) => C::Conflict,
867            BaseError::PluginCircularDependency(_) => C::Client,
868            BaseError::PluginDependencyMissing(_, _) => C::Client,
869            BaseError::PluginConfigInvalid(_, _) => C::Client,
870            BaseError::PluginNotFound(_)
871            | BaseError::PluginRegisterFailed(_, _)
872            | BaseError::PluginInitFailed(_, _)
873            | BaseError::PluginShutdownFailed(_, _)
874            | BaseError::PluginLifecycleFailed { .. } => C::Server,
875            // 数据库错误:连接失败/超时/连接池为瞬时(可重试),
876            // 已包装的 DbError 同理(底层连接/超时语义已由 From<DbError> 正确分桶)
877            BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
878                C::Transient
879            }
880            BaseError::MissingWhereClause(_) => C::Client,
881            BaseError::UnsupportedCapability(_) => C::Server,
882            BaseError::DatabaseAlreadyInitialized
883            | BaseError::DatabaseNotInitialized
884            | BaseError::DatabaseInitFailed(_)
885            | BaseError::DatasourceMismatch { .. } => C::Server,
886            // 事务失败可能是死锁(可重试)或约束违反(不可重试),保守归为 Server 避免无限重试
887            BaseError::DatabaseQueryFailed(_)
888            | BaseError::DatabaseExecuteFailed(_)
889            | BaseError::DatabaseTransactionFailed(_) => C::Server,
890            // Redis 错误:连接失败/超时/连接池为瞬时
891            BaseError::RedisConnectionFailed(_) => C::Transient,
892            BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
893            BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
894                match source.category() {
895                    yang_db::DbErrorCategory::Transient => C::Transient,
896                    yang_db::DbErrorCategory::Conflict => C::Conflict,
897                    yang_db::DbErrorCategory::Client => C::Client,
898                    yang_db::DbErrorCategory::NotFound => C::NotFound,
899                    yang_db::DbErrorCategory::Server => C::Server,
900                    _ => C::Server,
901                }
902            }
903            // HTTP 客户端错误
904            BaseError::HttpClientCreateFailed(_)
905            | BaseError::HttpClientNotInitialized
906            | BaseError::HttpClientAlreadyInitialized => C::Client,
907            // 解析失败是客户端编程错误(期望的响应类型不匹配),不是瞬时网络问题
908            BaseError::HttpResponseParseFailed(_) => C::Client,
909            BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
910            // 上游依赖不可用是瞬时故障:重试有意义(客户端应据 503 重试)。
911            BaseError::UpstreamUnavailable(_) => C::Transient,
912            // 熔断器打开意味着下游服务不健康,立即重试无济于事
913            BaseError::HttpCircuitBreakerOpen(_) => C::Server,
914            // 对端违约/谎报大小导致超出上限:非瞬时网络问题,与熔断器同类归为服务端
915            BaseError::HttpResponseTooLarge { .. } => C::Server,
916            // Token 错误
917            BaseError::TokenKeyInvalid(_)
918            | BaseError::TokenGenerateFailed(_)
919            | BaseError::TokenTypeInvalid(_)
920            | BaseError::TokenParseFailed(_) => C::Client,
921            BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
922                C::Auth
923            }
924            BaseError::TokenRevocationStateInvalid(_) => C::Server,
925            BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
926            BaseError::AuthorizationCheckUnavailable => C::Transient,
927            // 序列化错误
928            BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
929            // 字段验证错误
930            BaseError::InvalidFieldType(_, _)
931            | BaseError::InvalidEnumValue(_, _)
932            | BaseError::StringTooLong(_, _, _)
933            | BaseError::InvalidJsonFormat(_, _)
934            | BaseError::ValidationFailed(_, _)
935            | BaseError::FieldRequired(_)
936            | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
937            BaseError::FieldNotFound(_, _) => C::NotFound,
938            // Action 系统错误
939            BaseError::Unauthorized(_)
940            | BaseError::PermissionDenied(_)
941            | BaseError::SecondFactorRequired => C::Auth,
942            BaseError::ParamMissing(_)
943            | BaseError::ParamInvalid(_, _)
944            | BaseError::RateLimitExceeded { .. } => C::Client,
945            BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
946            BaseError::InvalidPassword => C::Auth,
947            BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
948            #[cfg(feature = "token")]
949            BaseError::StepUpRequired(_) => C::Client,
950            // 通用错误
951            BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
952        }
953    }
954
955    /// 取被包裹的底层数据库错误(不含 Redis 之外的其它传输错误)。
956    fn db_error(&self) -> Option<&yang_db::DbError> {
957        match self {
958            BaseError::DatabaseConnectionFailed(err)
959            | BaseError::DatabaseConnectionDbError(err)
960            | BaseError::DatabaseQueryFailed(err)
961            | BaseError::DatabaseExecuteFailed(err)
962            | BaseError::DatabaseTransactionFailed(err)
963            | BaseError::RedisConnectionFailed(err)
964            | BaseError::RedisOperationFailed(err)
965            | BaseError::RedisOperationDbError(err) => Some(err),
966            _ => None,
967        }
968    }
969
970    /// 暴露包裹的 SQLSTATE 结构化信息(含约束/表/列/诊断)。
971    ///
972    /// 外键、NOT NULL、CHECK 等约束错误在映射时保留原始 `DatabaseError`,
973    /// 调用方可据此分流,而无需解析本地化报文。
974    pub fn sql_error_info(&self) -> Option<&yang_db::SqlErrorInfo> {
975        match self.db_error()? {
976            yang_db::DbError::DatabaseError(info) => Some(info.as_ref()),
977            _ => None,
978        }
979    }
980
981    /// 原始 SQLSTATE 五字符码;无结构化数据库错误时返回 `None`。
982    pub fn sqlstate(&self) -> Option<&str> {
983        self.sql_error_info().map(yang_db::SqlErrorInfo::code)
984    }
985
986    /// 触发错误的约束名(如外键/唯一索引/CHECK 名称)。
987    pub fn constraint(&self) -> Option<&str> {
988        self.sql_error_info()
989            .and_then(yang_db::SqlErrorInfo::constraint)
990    }
991
992    /// 是否为可重试的瞬时错误。
993    ///
994    /// 包裹的 [`yang_db::DbError`] 以其自身 `is_retryable()` 为准:PostgreSQL
995    /// `40001`/`40P01`、`08xxx`、`53xxx` 可重试;`55P03`/`57014`/`25P02` 不可。
996    /// 非数据库错误沿用 [`BaseError::category`] 的 `Transient` 语义。
997    pub fn is_retryable(&self) -> bool {
998        self.db_error().map_or_else(
999            || self.category() == ErrorCategory::Transient,
1000            |err| err.is_retryable(),
1001        )
1002    }
1003
1004    /// 是否处于 PostgreSQL 的「事务已中止」状态(SQLSTATE `25P02`)。
1005    ///
1006    /// 此时任何语句都会继续失败,必须先 `ROLLBACK`。
1007    pub fn is_transaction_aborted(&self) -> bool {
1008        self.sql_error_info()
1009            .is_some_and(|info| info.kind() == yang_db::SqlErrorKind::InFailedTransaction)
1010    }
1011
1012    /// 是否为超时/取消类错误:`57014`(语句取消)或 `55P03`(锁不可用),
1013    /// 以及既有 HTTP 超时。
1014    pub fn is_timeout(&self) -> bool {
1015        matches!(self, BaseError::HttpTimeout)
1016            || self.sql_error_info().is_some_and(|info| {
1017                matches!(
1018                    info.kind(),
1019                    yang_db::SqlErrorKind::QueryCanceled | yang_db::SqlErrorKind::LockNotAvailable
1020                )
1021            })
1022    }
1023
1024    /// 是否为客户端过错(`Client`、`Auth` 或 `NotFound` 类)。
1025    ///
1026    /// 用于下游统一适配——客户端过错不可重试,调用方应修正请求而非重试。
1027    /// 注意 `Transient` **不**在此列:虽然瞬时错误也可归「服务端」,但它不是
1028    /// 调用方过错,且可重试——`is_server_error` 已覆盖该语义。
1029    pub fn is_client_error(&self) -> bool {
1030        matches!(
1031            self.category(),
1032            ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
1033        )
1034    }
1035
1036    /// 是否为服务端/基础设施错误(`Server`、`Transient` 或 `Conflict`)。
1037    ///
1038    /// 用于下游统一适配。`Transient` 在此视为服务端(可重试的服务端错误,
1039    /// 如连接超时 = HTTP 503 语义);`Conflict` 也计入(资源冲突 = HTTP 409,
1040    /// 但常由并发写引起而非纯调用方过错)。
1041    pub fn is_server_error(&self) -> bool {
1042        matches!(
1043            self.category(),
1044            ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
1045        )
1046    }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use super::*;
1052
1053    #[test]
1054    fn test_not_ready_code_is_stable() {
1055        assert_eq!(NOT_READY_CODE, 900001);
1056    }
1057
1058    #[test]
1059    fn test_error_codes_plugin() {
1060        assert_eq!(
1061            BaseError::PluginAlreadyRegistered("test".to_string()).code(),
1062            100001
1063        );
1064        assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
1065        assert_eq!(
1066            BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
1067            100003
1068        );
1069        assert_eq!(
1070            BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
1071            100004
1072        );
1073        assert_eq!(
1074            BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
1075            100005
1076        );
1077        assert_eq!(
1078            BaseError::PluginCircularDependency("test".to_string()).code(),
1079            100006
1080        );
1081        assert_eq!(
1082            BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
1083            100007
1084        );
1085        assert_eq!(
1086            BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
1087            100008
1088        );
1089    }
1090
1091    #[test]
1092    fn test_error_codes_database() {
1093        assert_eq!(
1094            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
1095                "reason".to_string()
1096            ))
1097            .code(),
1098            200001
1099        );
1100        assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
1101        assert_eq!(
1102            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
1103                .code(),
1104            200003
1105        );
1106        assert_eq!(
1107            BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
1108                .code(),
1109            200004
1110        );
1111        assert_eq!(
1112            BaseError::DatabaseInitFailed("reason".to_string()).code(),
1113            200005
1114        );
1115        assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
1116        assert_eq!(
1117            BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
1118                "reason".to_string()
1119            ))
1120            .code(),
1121            200009
1122        );
1123    }
1124
1125    #[cfg(feature = "http")]
1126    #[test]
1127    fn test_error_codes_http() {
1128        // 注意:reqwest::Error 无法直接构造,通过 code() 方法间接测试
1129        assert_eq!(
1130            BaseError::HttpResponseParseFailed("reason".to_string()).code(),
1131            300003
1132        );
1133        assert_eq!(BaseError::HttpTimeout.code(), 300004);
1134        assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
1135        assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
1136    }
1137
1138    #[cfg(feature = "token")]
1139    #[test]
1140    fn test_error_codes_token() {
1141        assert_eq!(
1142            BaseError::TokenKeyInvalid("reason".to_string()).code(),
1143            400001
1144        );
1145        assert_eq!(
1146            BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
1147                jsonwebtoken::errors::ErrorKind::InvalidToken
1148            ))
1149            .code(),
1150            400002
1151        );
1152        assert_eq!(
1153            BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
1154                jsonwebtoken::errors::ErrorKind::InvalidToken
1155            ))
1156            .code(),
1157            400003
1158        );
1159        assert_eq!(
1160            BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
1161                jsonwebtoken::errors::ErrorKind::InvalidToken
1162            ))
1163            .code(),
1164            400004
1165        );
1166        assert_eq!(BaseError::TokenExpired.code(), 400005);
1167        assert_eq!(
1168            BaseError::TokenTypeInvalid("reason".to_string()).code(),
1169            400006
1170        );
1171    }
1172
1173    #[test]
1174    fn test_error_codes_serialization() {
1175        assert_eq!(
1176            BaseError::JsonSerializeFailed("reason".to_string()).code(),
1177            500001
1178        );
1179        assert_eq!(
1180            BaseError::JsonDeserializeFailed("reason".to_string()).code(),
1181            500002
1182        );
1183    }
1184
1185    #[test]
1186    fn test_error_codes_field_validation() {
1187        assert_eq!(
1188            BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
1189            600001
1190        );
1191        assert_eq!(
1192            BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1193            600002
1194        );
1195        assert_eq!(
1196            BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1197            600003
1198        );
1199        assert_eq!(
1200            BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1201            600004
1202        );
1203        assert_eq!(
1204            BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1205            600005
1206        );
1207        assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1208        assert_eq!(
1209            BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1210            600007
1211        );
1212        assert_eq!(
1213            BaseError::FieldPermissionDenied(
1214                "table".to_string(),
1215                "field".to_string(),
1216                "reason".to_string()
1217            )
1218            .code(),
1219            600008
1220        );
1221    }
1222
1223    #[test]
1224    fn test_error_codes_action_system() {
1225        assert_eq!(
1226            BaseError::ActionNotFound("test_action".to_string()).code(),
1227            700001
1228        );
1229        assert_eq!(
1230            BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1231            700002
1232        );
1233        assert_eq!(
1234            BaseError::Unauthorized("Token 无效".to_string()).code(),
1235            700003
1236        );
1237        assert_eq!(
1238            BaseError::ParamMissing("user_id".to_string()).code(),
1239            700004
1240        );
1241        assert_eq!(
1242            BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1243            700005
1244        );
1245        assert_eq!(
1246            BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1247            700006
1248        );
1249        assert_eq!(
1250            BaseError::UserNotFound("user_123".to_string()).code(),
1251            700007
1252        );
1253        assert_eq!(BaseError::InvalidPassword.code(), 700008);
1254        assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1255        assert_eq!(
1256            BaseError::RateLimitExceeded {
1257                retry_after_seconds: 30
1258            }
1259            .code(),
1260            700011
1261        );
1262        assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
1263        assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
1264    }
1265
1266    #[test]
1267    fn test_error_codes_general() {
1268        assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1269        assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1270        assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1271    }
1272
1273    #[test]
1274    fn test_all_error_codes_are_nonzero() {
1275        // 确保所有错误码都是非零的
1276        let errors: Vec<BaseError> = vec![
1277            BaseError::PluginNotFound("test".to_string()),
1278            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1279            BaseError::HttpTimeout,
1280            BaseError::TokenExpired,
1281            BaseError::JsonSerializeFailed("test".to_string()),
1282            BaseError::FieldRequired("test".to_string()),
1283            BaseError::ActionNotFound("test".to_string()),
1284            BaseError::PermissionDenied("test".to_string()),
1285            BaseError::Unauthorized("test".to_string()),
1286            BaseError::ParamMissing("test".to_string()),
1287            BaseError::RecordNotFound("test".to_string()),
1288            BaseError::UserNotFound("test".to_string()),
1289            BaseError::InvalidPassword,
1290            BaseError::TableDefinitionNotSet,
1291            BaseError::RateLimitExceeded {
1292                retry_after_seconds: 30,
1293            },
1294            BaseError::Unknown("test".to_string()),
1295        ];
1296
1297        for error in errors {
1298            assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1299        }
1300    }
1301
1302    /// 测试数据库错误链 source() 可遍历
1303    #[test]
1304    fn test_database_error_source_chain() {
1305        use std::error::Error;
1306
1307        let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1308        let base_err = BaseError::DatabaseQueryFailed(db_err);
1309
1310        // BaseError.source() 应返回 Some,指向 DbError
1311        let source = base_err.source();
1312        assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1313    }
1314
1315    /// 测试 From<DbError> 转换保留错误链
1316    #[test]
1317    fn test_from_db_error_preserves_source() {
1318        use std::error::Error;
1319
1320        let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1321        let base_err: BaseError = db_err.into();
1322
1323        // 验证转换后仍可通过 source() 访问底层错误
1324        assert!(base_err.source().is_some());
1325        assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1326    }
1327
1328    #[test]
1329    fn test_redis_connection_and_operation_errors_preserve_db_source() {
1330        use std::error::Error;
1331
1332        let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1333            "connection refused".into(),
1334        ));
1335        let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1336            "WRONGTYPE".into(),
1337        ));
1338
1339        assert_eq!(connection.code(), 210001);
1340        assert_eq!(operation.code(), 210004);
1341        assert!(connection.source().is_some());
1342        assert!(operation.source().is_some());
1343    }
1344
1345    #[test]
1346    fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1347        use std::error::Error;
1348
1349        let error = BaseError::PluginLifecycleFailed {
1350            plugin: "audit".into(),
1351            stage: crate::plugin::PluginLifecycleStage::Shutdown,
1352            source: Box::new(std::io::Error::other("flush failed")),
1353        };
1354
1355        assert_eq!(error.code(), 100008);
1356        assert_eq!(error.code_str(), "100008");
1357        assert!(error.to_string().contains("audit"));
1358        assert!(error.to_string().contains("shutdown"));
1359        assert!(error.source().is_some());
1360    }
1361
1362    /// code_str() 必须与 code() 一致(metrics label 与数值码同源,防漂移)
1363    #[test]
1364    fn test_code_str_matches_code() {
1365        // 覆盖各域代表变体;新增变体时若两处不同步,此处会失败
1366        let samples: Vec<BaseError> = vec![
1367            BaseError::PluginNotFound("p".into()),
1368            BaseError::PluginLifecycleFailed {
1369                plugin: "p".into(),
1370                stage: crate::plugin::PluginLifecycleStage::Initialize,
1371                source: Box::new(std::io::Error::other("init")),
1372            },
1373            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1374            BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1375            BaseError::DatabaseNotInitialized,
1376            BaseError::RedisNotInitialized,
1377            BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1378            BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1379            BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1380            BaseError::HttpTimeout,
1381            BaseError::TokenExpired,
1382            BaseError::TokenRevoked,
1383            BaseError::TokenRevocationStateInvalid("invalid".into()),
1384            BaseError::AuthorizationStale,
1385            BaseError::AuthorizationVersionInvalid,
1386            BaseError::AuthorizationCheckUnavailable,
1387            BaseError::JsonSerializeFailed("s".into()),
1388            BaseError::FieldNotFound("t".into(), "f".into()),
1389            BaseError::ParamInvalid("k".into(), "r".into()),
1390            BaseError::TableDefinitionNotSet,
1391            BaseError::RateLimitExceeded {
1392                retry_after_seconds: 30,
1393            },
1394            BaseError::SecondFactorRequired,
1395            BaseError::ConfigError("c".into()),
1396            BaseError::Unknown("u".into()),
1397        ];
1398        for err in samples {
1399            let code = err.code();
1400            let code_str = err.code_str();
1401            assert_eq!(
1402                code_str.parse::<i32>().unwrap(),
1403                code,
1404                "code_str {:?} 与 code {} 不一致(变体 {:?})",
1405                code_str,
1406                code,
1407                err
1408            );
1409        }
1410    }
1411
1412    /// ErrorCategory 全变体覆盖:每个分类至少有一个代表性变体
1413    #[test]
1414    fn test_error_category_coverage() {
1415        // Client
1416        assert_eq!(
1417            BaseError::ParamInvalid("k".into(), "r".into()).category(),
1418            ErrorCategory::Client
1419        );
1420        assert_eq!(
1421            BaseError::ValidationFailed("f".into(), "r".into()).category(),
1422            ErrorCategory::Client
1423        );
1424        // Auth
1425        assert_eq!(
1426            BaseError::Unauthorized("u".into()).category(),
1427            ErrorCategory::Auth
1428        );
1429        assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1430        assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1431        assert_eq!(
1432            BaseError::SecondFactorRequired.category(),
1433            ErrorCategory::Auth
1434        );
1435        // NotFound
1436        assert_eq!(
1437            BaseError::RecordNotFound("r".into()).category(),
1438            ErrorCategory::NotFound
1439        );
1440        assert_eq!(
1441            BaseError::FieldNotFound("t".into(), "f".into()).category(),
1442            ErrorCategory::NotFound
1443        );
1444        // Conflict
1445        assert_eq!(
1446            BaseError::PluginAlreadyRegistered("p".into()).category(),
1447            ErrorCategory::Conflict
1448        );
1449        // Transient
1450        assert_eq!(
1451            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1452                .category(),
1453            ErrorCategory::Transient
1454        );
1455        assert_eq!(
1456            BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1457                .category(),
1458            ErrorCategory::Transient
1459        );
1460        assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1461        // Server
1462        assert_eq!(
1463            BaseError::Unknown("u".into()).category(),
1464            ErrorCategory::Server
1465        );
1466        assert_eq!(
1467            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1468            ErrorCategory::Server
1469        );
1470    }
1471
1472    /// is_retryable = (category == Transient)
1473    #[test]
1474    fn test_is_retryable() {
1475        assert!(
1476            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1477                .is_retryable()
1478        );
1479        assert!(BaseError::HttpTimeout.is_retryable());
1480        assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1481        assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1482        assert!(!BaseError::Unknown("u".into()).is_retryable());
1483    }
1484
1485    /// is_client_error = (Client | Auth | NotFound)
1486    #[test]
1487    fn test_is_client_error() {
1488        assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1489        assert!(BaseError::Unauthorized("u".into()).is_client_error());
1490        assert!(BaseError::TokenExpired.is_client_error());
1491        assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1492        assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1493        assert!(
1494            !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1495                .is_client_error()
1496        );
1497        assert!(!BaseError::Unknown("u".into()).is_client_error());
1498    }
1499
1500    /// is_server_error = (Server | Transient | Conflict)
1501    #[test]
1502    fn test_is_server_error() {
1503        assert!(BaseError::Unknown("u".into()).is_server_error());
1504        assert!(
1505            BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1506                .is_server_error()
1507        );
1508        assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1509        assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1510        assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1511    }
1512
1513    /// MySQL 唯一键冲突必须变成可归因的参数错误,而不是裸 DB 错误。
1514    #[test]
1515    fn mysql_duplicate_entry_maps_to_param_invalid_naming_the_key() {
1516        // 「Duplicate entry 'x' for key 'source_key'」是 MySQL 1062 的报文形态。
1517        // 系统自动派生 source_key、系统生成 token 都会撞唯一索引;裸 DB 错误会让
1518        // 控制台只能显示「数据库执行失败」,运维无从知道撞的是哪个键。
1519        let error = BaseError::from(yang_db::DbError::ConstraintError(
1520            "Duplicate entry 'payment_currency' for key 'source_key'".to_string(),
1521        ));
1522        match error {
1523            BaseError::ParamInvalid(field, message) => {
1524                assert_eq!(field, "source_key", "要点名冲突的键");
1525                assert!(!message.is_empty());
1526            }
1527            other => panic!("唯一键冲突应映射为 ParamInvalid,实际: {other:?}"),
1528        }
1529    }
1530
1531    /// 复合/限定形态:MySQL 8 可能把库名或表名带进 key。
1532    #[test]
1533    fn qualified_mysql_key_name_keeps_only_the_last_segment() {
1534        assert_eq!(
1535            duplicate_key_field(
1536                "Duplicate entry 'x' for key 'yang_system.feishu_datasource.source_key'"
1537            ),
1538            Some("source_key".to_string())
1539        );
1540    }
1541
1542    /// PostgreSQL 的唯一约束冲突(23505)同样要归因到可读的名字。
1543    #[test]
1544    fn postgres_unique_violation_maps_to_param_invalid() {
1545        let error = BaseError::from(yang_db::DbError::ConstraintError(
1546            "duplicate key value violates unique constraint \"feishu_option_option_id_key\""
1547                .to_string(),
1548        ));
1549        match error {
1550            BaseError::ParamInvalid(field, _) => assert_eq!(field, "feishu_option_option_id_key"),
1551            other => panic!("PG 唯一约束冲突应映射为 ParamInvalid,实际: {other:?}"),
1552        }
1553    }
1554
1555    /// 回归守卫:约束错误里**只有**唯一键冲突该变成 ParamInvalid。
1556    ///
1557    /// 外键、非空、CHECK 与唯一键在 MySQL 上共用同一个 SQLSTATE(23000),
1558    /// 把它们也吞成「参数非法」会让真正的数据完整性问题显示成用户的输入错误。
1559    #[test]
1560    fn other_constraint_errors_keep_their_own_mapping() {
1561        for message in [
1562            "Cannot add or update a child row: a foreign key constraint fails",
1563            "Column 'title' cannot be null",
1564            "Check constraint 'positive_amount' is violated",
1565        ] {
1566            let error = BaseError::from(yang_db::DbError::ConstraintError(message.to_string()));
1567            assert!(
1568                !matches!(error, BaseError::ParamInvalid(_, _)),
1569                "{message:?} 不该被当成参数非法,实际: {error:?}"
1570            );
1571        }
1572    }
1573
1574    /// 报文提取本身是纯函数,单独钉住它的边界。
1575    #[test]
1576    fn duplicate_key_field_returns_none_for_unrecognised_messages() {
1577        assert_eq!(duplicate_key_field(""), None);
1578        assert_eq!(
1579            duplicate_key_field("Duplicate entry 'x'"),
1580            None,
1581            "缺 for key 段就该放弃提取,而不是编一个名字出来"
1582        );
1583        assert_eq!(duplicate_key_field("some other db error"), None);
1584    }
1585
1586    fn sql_error(code: &str, constraint: Option<&str>) -> BaseError {
1587        let mut info = yang_db::SqlErrorInfo::new(code, format!("sqlstate {code}"));
1588        if let Some(constraint) = constraint {
1589            info = info.with_constraint(Some(constraint.to_string()));
1590        }
1591        BaseError::DatabaseExecuteFailed(yang_db::DbError::DatabaseError(Box::new(info)))
1592    }
1593
1594    /// P0-13/P1-17:SQLSTATE 语义(可重试 / 取消超时 / 事务中止)必须从包裹的
1595    /// `yang_db::DbError` 透出,而不是被「数据库执行失败」压平。
1596    #[test]
1597    fn sqlstate_semantics_are_exposed_from_wrapped_db_error() {
1598        // 40001 序列化失败、40P01 死锁:可重试。
1599        for code in ["40001", "40P01"] {
1600            let error = sql_error(code, None);
1601            assert!(error.is_retryable(), "{code} 应可重试");
1602            assert!(!error.is_timeout(), "{code} 不是超时");
1603            assert!(!error.is_transaction_aborted(), "{code} 不是事务中止");
1604        }
1605
1606        // 08xxx 连接失败、53xxx 资源不足:可重试。
1607        assert!(sql_error("08006", None).is_retryable());
1608        assert!(sql_error("53300", None).is_retryable());
1609
1610        // 55P03 锁不可用、57014 语句取消:不可重试,但属于超时/取消。
1611        for code in ["55P03", "57014"] {
1612            let error = sql_error(code, None);
1613            assert!(!error.is_retryable(), "{code} 不应自动重试");
1614            assert!(error.is_timeout(), "{code} 应识别为超时/取消");
1615        }
1616
1617        // 25P02 事务已中止:不可重试,且必须显式识别以触发 ROLLBACK。
1618        let aborted = sql_error("25P02", None);
1619        assert!(aborted.is_transaction_aborted());
1620        assert!(!aborted.is_retryable());
1621        assert!(!aborted.is_timeout());
1622        assert!(!sql_error("40001", None).is_transaction_aborted());
1623    }
1624
1625    /// 外键/NOT NULL/CHECK 违反保留 SQLSTATE 与约束名,供 409/422 分流。
1626    #[test]
1627    fn constraint_errors_keep_sqlstate_and_constraint_context() {
1628        let foreign_key = sql_error("23503", Some("orders_user_id_fkey"));
1629        assert_eq!(foreign_key.sqlstate(), Some("23503"));
1630        assert_eq!(foreign_key.constraint(), Some("orders_user_id_fkey"));
1631        assert!(!foreign_key.is_retryable());
1632        assert!(foreign_key.is_server_error());
1633
1634        let not_null = sql_error("23502", Some("users_email_not_null"));
1635        assert_eq!(not_null.sqlstate(), Some("23502"));
1636        assert_eq!(not_null.constraint(), Some("users_email_not_null"));
1637
1638        let check = sql_error("23514", Some("positive_amount"));
1639        assert_eq!(check.constraint(), Some("positive_amount"));
1640
1641        // 非结构化错误没有 SQLSTATE 上下文。
1642        let plain = BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("boom".into()));
1643        assert_eq!(plain.sqlstate(), None);
1644        assert_eq!(plain.constraint(), None);
1645    }
1646}