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/// 系统统一错误类型
23///
24/// 包含所有模块的错误变体,使用中文错误消息
25#[derive(Debug, Error)]
26pub enum BaseError {
27    // ==================== 插件管理错误 ====================
28    /// 插件已注册
29    #[error("插件已注册: {0}")]
30    PluginAlreadyRegistered(String),
31
32    /// 插件未找到
33    #[error("插件未找到: {0}")]
34    PluginNotFound(String),
35
36    /// 插件注册失败
37    #[error("插件注册失败 [{0}]: {1}")]
38    PluginRegisterFailed(String, String),
39
40    /// 插件初始化失败
41    #[error("插件初始化失败 [{0}]: {1}")]
42    PluginInitFailed(String, String),
43
44    /// 插件依赖缺失
45    #[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
46    PluginDependencyMissing(String, String),
47
48    /// 插件循环依赖
49    #[error("插件循环依赖: {0}")]
50    PluginCircularDependency(String),
51
52    /// 插件配置无效
53    #[error("插件配置无效 [{0}]: {1}")]
54    PluginConfigInvalid(String, String),
55
56    /// 插件关闭失败
57    #[error("插件关闭失败 [{0}]: {1}")]
58    PluginShutdownFailed(String, String),
59
60    // ==================== 数据库错误 ====================
61    /// 数据库连接失败
62    #[error("数据库连接失败: {0}")]
63    DatabaseConnectionFailed(String),
64
65    /// 数据库已初始化
66    #[error("数据库已初始化")]
67    DatabaseAlreadyInitialized,
68
69    /// 数据库查询失败,持有底层 DbError 以保留错误链
70    #[error("数据库查询失败: {0}")]
71    DatabaseQueryFailed(#[source] yang_db::DbError),
72
73    /// 数据库执行失败,持有底层 DbError 以保留错误链
74    #[error("数据库执行失败: {0}")]
75    DatabaseExecuteFailed(#[source] yang_db::DbError),
76
77    /// 数据库初始化失败
78    #[error("数据库初始化失败: {0}")]
79    DatabaseInitFailed(String),
80
81    /// 数据库迁移失败
82    #[error("数据库迁移失败 [{0}]: {1}")]
83    DatabaseMigrationFailed(String, String),
84
85    /// 迁移失败(别名)
86    #[error("迁移失败 [{0}] v{1}: {2}")]
87    MigrationFailed(String, String, String),
88
89    /// 数据库未初始化
90    #[error("数据库未初始化")]
91    DatabaseNotInitialized,
92
93    /// 数据库事务失败,持有底层 DbError 以保留错误链
94    #[error("数据库事务失败: {0}")]
95    DatabaseTransactionFailed(#[source] yang_db::DbError),
96
97    // ==================== Redis 错误 ====================
98    /// Redis 连接失败
99    #[error("Redis 连接失败: {0}")]
100    RedisConnectionFailed(String),
101
102    /// Redis 已初始化
103    #[error("Redis 已初始化")]
104    RedisAlreadyInitialized,
105
106    /// Redis 未初始化
107    #[error("Redis 未初始化")]
108    RedisNotInitialized,
109
110    /// Redis 操作失败
111    #[error("Redis 操作失败: {0}")]
112    RedisOperationFailed(String),
113
114    // ==================== HTTP 客户端错误 ====================
115    /// HTTP 客户端创建失败,持有底层 reqwest::Error 以保留错误链
116    #[cfg(feature = "http")]
117    #[error("HTTP 客户端创建失败: {0}")]
118    HttpClientCreateFailed(#[source] reqwest::Error),
119
120    /// HTTP 客户端创建失败(无 http feature 时使用字符串)
121    #[cfg(not(feature = "http"))]
122    #[error("HTTP 客户端创建失败: {0}")]
123    HttpClientCreateFailed(String),
124
125    /// HTTP 请求失败,持有底层 reqwest::Error 以保留错误链
126    #[cfg(feature = "http")]
127    #[error("HTTP 请求失败: {0}")]
128    HttpRequestFailed(#[source] reqwest::Error),
129
130    /// HTTP 请求失败(无 http feature 时使用字符串)
131    #[cfg(not(feature = "http"))]
132    #[error("HTTP 请求失败: {0}")]
133    HttpRequestFailed(String),
134
135    /// HTTP 响应解析失败
136    #[error("HTTP 响应解析失败: {0}")]
137    HttpResponseParseFailed(String),
138
139    /// HTTP 超时
140    #[error("HTTP 请求超时")]
141    HttpTimeout,
142
143    /// HTTP 客户端已初始化
144    #[error("HTTP 客户端已初始化")]
145    HttpClientAlreadyInitialized,
146
147    /// HTTP 客户端未初始化
148    #[error("HTTP 客户端未初始化")]
149    HttpClientNotInitialized,
150
151    // ==================== Token 管理错误 ====================
152    /// Token 密钥无效
153    #[error("Token 密钥无效: {0}")]
154    TokenKeyInvalid(String),
155
156    /// Token 生成失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
157    #[cfg(feature = "token")]
158    #[error("Token 生成失败: {0}")]
159    TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
160
161    /// Token 生成失败(无 token feature 时使用字符串)
162    #[cfg(not(feature = "token"))]
163    #[error("Token 生成失败: {0}")]
164    TokenGenerateFailed(String),
165
166    /// Token 验证失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
167    #[cfg(feature = "token")]
168    #[error("Token 验证失败: {0}")]
169    TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
170
171    /// Token 验证失败(无 token feature 时使用字符串)
172    #[cfg(not(feature = "token"))]
173    #[error("Token 验证失败: {0}")]
174    TokenVerifyFailed(String),
175
176    /// Token 解析失败,持有底层 jsonwebtoken::errors::Error 以保留错误链
177    #[cfg(feature = "token")]
178    #[error("Token 解析失败: {0}")]
179    TokenParseFailed(#[source] jsonwebtoken::errors::Error),
180
181    /// Token 解析失败(无 token feature 时使用字符串)
182    #[cfg(not(feature = "token"))]
183    #[error("Token 解析失败: {0}")]
184    TokenParseFailed(String),
185
186    /// Token 已过期
187    #[error("Token 已过期")]
188    TokenExpired,
189
190    /// Token 类型无效
191    #[error("Token 类型无效: {0}")]
192    TokenTypeInvalid(String),
193
194    // ==================== 序列化错误 ====================
195    /// JSON 序列化失败
196    #[error("JSON 序列化失败: {0}")]
197    JsonSerializeFailed(String),
198
199    /// JSON 反序列化失败
200    #[error("JSON 反序列化失败: {0}")]
201    JsonDeserializeFailed(String),
202
203    // ==================== 字段验证错误 ====================
204    /// 字段类型无效
205    #[error("字段类型无效 [{0}]: {1}")]
206    InvalidFieldType(String, String),
207
208    /// 枚举值无效
209    #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
210    InvalidEnumValue(String, String),
211
212    /// 字符串长度超出限制
213    #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
214    StringTooLong(String, usize, usize),
215
216    /// JSON 格式无效
217    #[error("JSON 格式无效 [{0}]: {1}")]
218    InvalidJsonFormat(String, String),
219
220    /// 验证失败
221    #[error("验证失败 [{0}]: {1}")]
222    ValidationFailed(String, String),
223
224    /// 字段必填
225    #[error("字段必填: {0}")]
226    FieldRequired(String),
227
228    /// 字段未找到
229    #[error("字段未找到 [表: {0}]: {1}")]
230    FieldNotFound(String, String),
231
232    /// 字段权限被拒绝
233    #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
234    FieldPermissionDenied(String, String, String),
235
236    // ==================== Action 系统错误 ====================
237    /// Action 未找到
238    #[error("Action 未找到: {0}")]
239    ActionNotFound(String),
240
241    /// 权限被拒绝
242    #[error("权限被拒绝: {0}")]
243    PermissionDenied(String),
244
245    /// 未授权
246    #[error("未授权: {0}")]
247    Unauthorized(String),
248
249    /// 参数缺失
250    #[error("参数缺失: {0}")]
251    ParamMissing(String),
252
253    /// 参数无效
254    #[error("参数无效 [{0}]: {1}")]
255    ParamInvalid(String, String),
256
257    /// 记录未找到
258    #[error("记录未找到: {0}")]
259    RecordNotFound(String),
260
261    /// 用户未找到
262    #[error("用户未找到: {0}")]
263    UserNotFound(String),
264
265    /// 密码无效
266    #[error("密码无效")]
267    InvalidPassword,
268
269    /// 表配置未设置
270    #[error("表配置未设置")]
271    TableConfigNotSet,
272
273    // ==================== 通用错误 ====================
274    /// 配置错误
275    #[error("配置错误: {0}")]
276    ConfigError(String),
277
278    /// IO 错误
279    #[error("IO 错误: {0}")]
280    IoError(String),
281
282    /// 未知错误
283    #[error("未知错误: {0}")]
284    Unknown(String),
285}
286
287// ==================== From trait 实现 ====================
288
289/// 从 yang_db::DbError 转换为 BaseError
290///
291/// 按 DbError 变体分类映射到对应的 BaseError 变体:
292/// - 查询类 → DatabaseQueryFailed
293/// - 执行类 → DatabaseExecuteFailed
294/// - 事务类 → DatabaseTransactionFailed
295/// - 连接类 → DatabaseConnectionFailed
296/// - Redis 类 → RedisOperationFailed
297impl From<yang_db::DbError> for BaseError {
298    fn from(err: yang_db::DbError) -> Self {
299        use yang_db::DbError as D;
300        match &err {
301            // 查询类:查询错误、表不存在、类型转换、反序列化、不支持的操作符、未知错误
302            D::QueryError(_)
303            | D::TableNotFound(_)
304            | D::TypeConversionError(_)
305            | D::DeserializationError(_)
306            | D::UnsupportedOperator(_)
307            | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
308
309            // 执行类:约束错误、SQL 语法错误、缺少 WHERE 条件、缺少 GROUP BY、序列化错误
310            D::ConstraintError(_)
311            | D::SqlSyntaxError(_)
312            | D::MissingWhereClause
313            | D::MissingGroupByClause
314            | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
315
316            // 事务类:事务错误
317            D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
318
319            // 连接类:连接错误(使用字符串,因为 DatabaseConnectionFailed 持有 String)
320            D::ConnectionError(_) => BaseError::DatabaseConnectionFailed(err.to_string()),
321
322            // Redis 类:所有 Redis 相关错误(使用字符串,因为 RedisOperationFailed 持有 String)
323            D::RedisConnectionError(_)
324            | D::RedisCommandError(_)
325            | D::RedisPoolError(_)
326            | D::RedisTypeConversionError(_)
327            | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err.to_string()),
328        }
329    }
330}
331
332/// 从 std::io::Error 转换为 BaseError
333impl From<std::io::Error> for BaseError {
334    fn from(err: std::io::Error) -> Self {
335        BaseError::IoError(err.to_string())
336    }
337}
338
339/// 从 serde_json::Error 转换为 BaseError
340impl From<serde_json::Error> for BaseError {
341    fn from(err: serde_json::Error) -> Self {
342        if err.is_syntax() || err.is_data() || err.is_eof() {
343            BaseError::JsonDeserializeFailed(err.to_string())
344        } else {
345            BaseError::JsonSerializeFailed(err.to_string())
346        }
347    }
348}
349
350/// 从 reqwest::Error 转换为 BaseError
351#[cfg(feature = "http")]
352impl From<reqwest::Error> for BaseError {
353    fn from(err: reqwest::Error) -> Self {
354        if err.is_timeout() {
355            BaseError::HttpTimeout
356        } else if err.is_connect() {
357            BaseError::HttpClientCreateFailed(err)
358        } else {
359            BaseError::HttpRequestFailed(err)
360        }
361    }
362}
363
364/// 从 jsonwebtoken::errors::Error 转换为 BaseError
365///
366/// 按 ErrorKind 分类映射:
367/// - ExpiredSignature → TokenExpired
368/// - InvalidToken / InvalidSignature → TokenVerifyFailed
369/// - 其他 → TokenParseFailed
370#[cfg(feature = "token")]
371impl From<jsonwebtoken::errors::Error> for BaseError {
372    fn from(err: jsonwebtoken::errors::Error) -> Self {
373        use jsonwebtoken::errors::ErrorKind;
374        match err.kind() {
375            ErrorKind::ExpiredSignature => BaseError::TokenExpired,
376            ErrorKind::InvalidToken | ErrorKind::InvalidSignature => {
377                BaseError::TokenVerifyFailed(err)
378            }
379            _ => BaseError::TokenParseFailed(err),
380        }
381    }
382}
383
384impl BaseError {
385    /// 获取错误码
386    ///
387    /// 返回与错误类型对应的数字错误码,用于 API 响应
388    ///
389    /// # 错误码规范
390    ///
391    /// - 1xxxxx: 插件管理错误
392    /// - 2xxxxx: 数据库错误
393    /// - 3xxxxx: HTTP 客户端错误
394    /// - 4xxxxx: Token 管理错误
395    /// - 5xxxxx: 序列化错误
396    /// - 6xxxxx: 字段验证错误
397    /// - 7xxxxx: Action 系统错误
398    /// - 9xxxxx: 通用错误
399    ///
400    /// # 返回
401    ///
402    /// - 错误码(非零整数)
403    ///
404    /// # 示例
405    ///
406    /// ```rust,ignore
407    /// use yang_base::error::BaseError;
408    ///
409    /// let error = BaseError::FieldRequired("username".to_string());
410    /// assert_eq!(error.code(), 600006);
411    /// ```
412    pub fn code(&self) -> i32 {
413        match self {
414            // ==================== 插件管理错误 (1xxxxx) ====================
415            BaseError::PluginAlreadyRegistered(_) => 100001,
416            BaseError::PluginNotFound(_) => 100002,
417            BaseError::PluginRegisterFailed(_, _) => 100003,
418            BaseError::PluginInitFailed(_, _) => 100004,
419            BaseError::PluginDependencyMissing(_, _) => 100005,
420            BaseError::PluginCircularDependency(_) => 100006,
421            BaseError::PluginConfigInvalid(_, _) => 100007,
422            BaseError::PluginShutdownFailed(_, _) => 100008,
423
424            // ==================== 数据库错误 (2xxxxx) ====================
425            BaseError::DatabaseConnectionFailed(_) => 200001,
426            BaseError::DatabaseAlreadyInitialized => 200002,
427            BaseError::DatabaseQueryFailed(_) => 200003,
428            BaseError::DatabaseExecuteFailed(_) => 200004,
429            BaseError::DatabaseInitFailed(_) => 200005,
430            BaseError::DatabaseMigrationFailed(_, _) => 200006,
431            BaseError::MigrationFailed(_, _, _) => 200007,
432            BaseError::DatabaseNotInitialized => 200008,
433            BaseError::DatabaseTransactionFailed(_) => 200009,
434
435            // ==================== Redis 错误 (21xxxx) ====================
436            BaseError::RedisConnectionFailed(_) => 210001,
437            BaseError::RedisAlreadyInitialized => 210002,
438            BaseError::RedisNotInitialized => 210003,
439            BaseError::RedisOperationFailed(_) => 210004,
440
441            // ==================== HTTP 客户端错误 (3xxxxx) ====================
442            BaseError::HttpClientCreateFailed(_) => 300001,
443            BaseError::HttpRequestFailed(_) => 300002,
444            BaseError::HttpResponseParseFailed(_) => 300003,
445            BaseError::HttpTimeout => 300004,
446            BaseError::HttpClientAlreadyInitialized => 300005,
447            BaseError::HttpClientNotInitialized => 300006,
448
449            // ==================== Token 管理错误 (4xxxxx) ====================
450            BaseError::TokenKeyInvalid(_) => 400001,
451            BaseError::TokenGenerateFailed(_) => 400002,
452            BaseError::TokenVerifyFailed(_) => 400003,
453            BaseError::TokenParseFailed(_) => 400004,
454            BaseError::TokenExpired => 400005,
455            BaseError::TokenTypeInvalid(_) => 400006,
456
457            // ==================== 序列化错误 (5xxxxx) ====================
458            BaseError::JsonSerializeFailed(_) => 500001,
459            BaseError::JsonDeserializeFailed(_) => 500002,
460
461            // ==================== 字段验证错误 (6xxxxx) ====================
462            BaseError::InvalidFieldType(_, _) => 600001,
463            BaseError::InvalidEnumValue(_, _) => 600002,
464            BaseError::StringTooLong(_, _, _) => 600003,
465            BaseError::InvalidJsonFormat(_, _) => 600004,
466            BaseError::ValidationFailed(_, _) => 600005,
467            BaseError::FieldRequired(_) => 600006,
468            BaseError::FieldNotFound(_, _) => 600007,
469            BaseError::FieldPermissionDenied(_, _, _) => 600008,
470
471            // ==================== Action 系统错误 (7xxxxx) ====================
472            BaseError::ActionNotFound(_) => 700001,
473            BaseError::PermissionDenied(_) => 700002,
474            BaseError::Unauthorized(_) => 700003,
475            BaseError::ParamMissing(_) => 700004,
476            BaseError::ParamInvalid(_, _) => 700005,
477            BaseError::RecordNotFound(_) => 700006,
478            BaseError::UserNotFound(_) => 700007,
479            BaseError::InvalidPassword => 700008,
480            BaseError::TableConfigNotSet => 700009,
481
482            // ==================== 通用错误 (9xxxxx) ====================
483            BaseError::ConfigError(_) => 900001,
484            BaseError::IoError(_) => 900002,
485            BaseError::Unknown(_) => 999999,
486        }
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493
494    #[test]
495    fn test_error_codes_plugin() {
496        assert_eq!(
497            BaseError::PluginAlreadyRegistered("test".to_string()).code(),
498            100001
499        );
500        assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
501        assert_eq!(
502            BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
503            100003
504        );
505        assert_eq!(
506            BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
507            100004
508        );
509        assert_eq!(
510            BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
511            100005
512        );
513        assert_eq!(
514            BaseError::PluginCircularDependency("test".to_string()).code(),
515            100006
516        );
517        assert_eq!(
518            BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
519            100007
520        );
521        assert_eq!(
522            BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
523            100008
524        );
525    }
526
527    #[test]
528    fn test_error_codes_database() {
529        assert_eq!(
530            BaseError::DatabaseConnectionFailed("reason".to_string()).code(),
531            200001
532        );
533        assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
534        assert_eq!(
535            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
536                .code(),
537            200003
538        );
539        assert_eq!(
540            BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
541                .code(),
542            200004
543        );
544        assert_eq!(
545            BaseError::DatabaseInitFailed("reason".to_string()).code(),
546            200005
547        );
548        assert_eq!(
549            BaseError::DatabaseMigrationFailed("plugin".to_string(), "reason".to_string()).code(),
550            200006
551        );
552        assert_eq!(
553            BaseError::MigrationFailed(
554                "plugin".to_string(),
555                "v1".to_string(),
556                "reason".to_string()
557            )
558            .code(),
559            200007
560        );
561        assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
562        assert_eq!(
563            BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
564                "reason".to_string()
565            ))
566            .code(),
567            200009
568        );
569    }
570
571    #[cfg(feature = "http")]
572    #[test]
573    fn test_error_codes_http() {
574        // 注意:reqwest::Error 无法直接构造,通过 code() 方法间接测试
575        assert_eq!(
576            BaseError::HttpResponseParseFailed("reason".to_string()).code(),
577            300003
578        );
579        assert_eq!(BaseError::HttpTimeout.code(), 300004);
580        assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
581        assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
582    }
583
584    #[cfg(feature = "token")]
585    #[test]
586    fn test_error_codes_token() {
587        assert_eq!(
588            BaseError::TokenKeyInvalid("reason".to_string()).code(),
589            400001
590        );
591        assert_eq!(
592            BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
593                jsonwebtoken::errors::ErrorKind::InvalidToken
594            ))
595            .code(),
596            400002
597        );
598        assert_eq!(
599            BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
600                jsonwebtoken::errors::ErrorKind::InvalidToken
601            ))
602            .code(),
603            400003
604        );
605        assert_eq!(
606            BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
607                jsonwebtoken::errors::ErrorKind::InvalidToken
608            ))
609            .code(),
610            400004
611        );
612        assert_eq!(BaseError::TokenExpired.code(), 400005);
613        assert_eq!(
614            BaseError::TokenTypeInvalid("reason".to_string()).code(),
615            400006
616        );
617    }
618
619    #[test]
620    fn test_error_codes_serialization() {
621        assert_eq!(
622            BaseError::JsonSerializeFailed("reason".to_string()).code(),
623            500001
624        );
625        assert_eq!(
626            BaseError::JsonDeserializeFailed("reason".to_string()).code(),
627            500002
628        );
629    }
630
631    #[test]
632    fn test_error_codes_field_validation() {
633        assert_eq!(
634            BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
635            600001
636        );
637        assert_eq!(
638            BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
639            600002
640        );
641        assert_eq!(
642            BaseError::StringTooLong("field".to_string(), 100, 50).code(),
643            600003
644        );
645        assert_eq!(
646            BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
647            600004
648        );
649        assert_eq!(
650            BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
651            600005
652        );
653        assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
654        assert_eq!(
655            BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
656            600007
657        );
658        assert_eq!(
659            BaseError::FieldPermissionDenied(
660                "table".to_string(),
661                "field".to_string(),
662                "reason".to_string()
663            )
664            .code(),
665            600008
666        );
667    }
668
669    #[test]
670    fn test_error_codes_action_system() {
671        assert_eq!(
672            BaseError::ActionNotFound("test_action".to_string()).code(),
673            700001
674        );
675        assert_eq!(
676            BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
677            700002
678        );
679        assert_eq!(
680            BaseError::Unauthorized("Token 无效".to_string()).code(),
681            700003
682        );
683        assert_eq!(
684            BaseError::ParamMissing("user_id".to_string()).code(),
685            700004
686        );
687        assert_eq!(
688            BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
689            700005
690        );
691        assert_eq!(
692            BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
693            700006
694        );
695        assert_eq!(
696            BaseError::UserNotFound("user_123".to_string()).code(),
697            700007
698        );
699        assert_eq!(BaseError::InvalidPassword.code(), 700008);
700        assert_eq!(BaseError::TableConfigNotSet.code(), 700009);
701    }
702
703    #[test]
704    fn test_error_codes_general() {
705        assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
706        assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
707        assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
708    }
709
710    #[test]
711    fn test_all_error_codes_are_nonzero() {
712        // 确保所有错误码都是非零的
713        let errors: Vec<BaseError> = vec![
714            BaseError::PluginNotFound("test".to_string()),
715            BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
716            BaseError::HttpTimeout,
717            BaseError::TokenExpired,
718            BaseError::JsonSerializeFailed("test".to_string()),
719            BaseError::FieldRequired("test".to_string()),
720            BaseError::ActionNotFound("test".to_string()),
721            BaseError::PermissionDenied("test".to_string()),
722            BaseError::Unauthorized("test".to_string()),
723            BaseError::ParamMissing("test".to_string()),
724            BaseError::RecordNotFound("test".to_string()),
725            BaseError::UserNotFound("test".to_string()),
726            BaseError::InvalidPassword,
727            BaseError::TableConfigNotSet,
728            BaseError::Unknown("test".to_string()),
729        ];
730
731        for error in errors {
732            assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
733        }
734    }
735
736    /// 测试数据库错误链 source() 可遍历
737    #[test]
738    fn test_database_error_source_chain() {
739        use std::error::Error;
740
741        let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
742        let base_err = BaseError::DatabaseQueryFailed(db_err);
743
744        // BaseError.source() 应返回 Some,指向 DbError
745        let source = base_err.source();
746        assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
747    }
748
749    /// 测试 From<DbError> 转换保留错误链
750    #[test]
751    fn test_from_db_error_preserves_source() {
752        use std::error::Error;
753
754        let db_err = yang_db::DbError::QueryError("查询失败".to_string());
755        let base_err: BaseError = db_err.into();
756
757        // 验证转换后仍可通过 source() 访问底层错误
758        assert!(base_err.source().is_some());
759        assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
760    }
761}