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