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