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    /// 数据库查询失败
70    #[error("数据库查询失败: {0}")]
71    DatabaseQueryFailed(String),
72
73    /// 数据库执行失败
74    #[error("数据库执行失败: {0}")]
75    DatabaseExecuteFailed(String),
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    /// 数据库事务失败
94    #[error("数据库事务失败: {0}")]
95    DatabaseTransactionFailed(String),
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 客户端创建失败
116    #[error("HTTP 客户端创建失败: {0}")]
117    HttpClientCreateFailed(String),
118
119    /// HTTP 请求失败
120    #[error("HTTP 请求失败: {0}")]
121    HttpRequestFailed(String),
122
123    /// HTTP 响应解析失败
124    #[error("HTTP 响应解析失败: {0}")]
125    HttpResponseParseFailed(String),
126
127    /// HTTP 超时
128    #[error("HTTP 请求超时")]
129    HttpTimeout,
130
131    // ==================== Token 管理错误 ====================
132    /// Token 密钥无效
133    #[error("Token 密钥无效: {0}")]
134    TokenKeyInvalid(String),
135
136    /// Token 生成失败
137    #[error("Token 生成失败: {0}")]
138    TokenGenerateFailed(String),
139
140    /// Token 验证失败
141    #[error("Token 验证失败: {0}")]
142    TokenVerifyFailed(String),
143
144    /// Token 解析失败
145    #[error("Token 解析失败: {0}")]
146    TokenParseFailed(String),
147
148    /// Token 已过期
149    #[error("Token 已过期")]
150    TokenExpired,
151
152    /// Token 类型无效
153    #[error("Token 类型无效: {0}")]
154    TokenTypeInvalid(String),
155
156    // ==================== 序列化错误 ====================
157    /// JSON 序列化失败
158    #[error("JSON 序列化失败: {0}")]
159    JsonSerializeFailed(String),
160
161    /// JSON 反序列化失败
162    #[error("JSON 反序列化失败: {0}")]
163    JsonDeserializeFailed(String),
164
165    // ==================== 字段验证错误 ====================
166    /// 字段类型无效
167    #[error("字段类型无效 [{0}]: {1}")]
168    InvalidFieldType(String, String),
169
170    /// 枚举值无效
171    #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
172    InvalidEnumValue(String, String),
173
174    /// 字符串长度超出限制
175    #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
176    StringTooLong(String, usize, usize),
177
178    /// JSON 格式无效
179    #[error("JSON 格式无效 [{0}]: {1}")]
180    InvalidJsonFormat(String, String),
181
182    /// 验证失败
183    #[error("验证失败 [{0}]: {1}")]
184    ValidationFailed(String, String),
185
186    /// 字段必填
187    #[error("字段必填: {0}")]
188    FieldRequired(String),
189
190    /// 字段未找到
191    #[error("字段未找到 [表: {0}]: {1}")]
192    FieldNotFound(String, String),
193
194    /// 字段权限被拒绝
195    #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
196    FieldPermissionDenied(String, String, String),
197
198    // ==================== Action 系统错误 ====================
199    /// Action 未找到
200    #[error("Action 未找到: {0}")]
201    ActionNotFound(String),
202
203    /// 权限被拒绝
204    #[error("权限被拒绝: {0}")]
205    PermissionDenied(String),
206
207    /// 未授权
208    #[error("未授权: {0}")]
209    Unauthorized(String),
210
211    /// 参数缺失
212    #[error("参数缺失: {0}")]
213    ParamMissing(String),
214
215    /// 参数无效
216    #[error("参数无效 [{0}]: {1}")]
217    ParamInvalid(String, String),
218
219    /// 记录未找到
220    #[error("记录未找到: {0}")]
221    RecordNotFound(String),
222
223    /// 用户未找到
224    #[error("用户未找到: {0}")]
225    UserNotFound(String),
226
227    /// 密码无效
228    #[error("密码无效")]
229    InvalidPassword,
230
231    /// 表配置未设置
232    #[error("表配置未设置")]
233    TableConfigNotSet,
234
235    // ==================== 通用错误 ====================
236    /// 配置错误
237    #[error("配置错误: {0}")]
238    ConfigError(String),
239
240    /// IO 错误
241    #[error("IO 错误: {0}")]
242    IoError(String),
243
244    /// 未知错误
245    #[error("未知错误: {0}")]
246    Unknown(String),
247}
248
249// ==================== From trait 实现 ====================
250
251/// 从 yang_db::DbError 转换为 BaseError
252impl From<yang_db::DbError> for BaseError {
253    fn from(err: yang_db::DbError) -> Self {
254        BaseError::DatabaseQueryFailed(err.to_string())
255    }
256}
257
258/// 从 std::io::Error 转换为 BaseError
259impl From<std::io::Error> for BaseError {
260    fn from(err: std::io::Error) -> Self {
261        BaseError::IoError(err.to_string())
262    }
263}
264
265/// 从 serde_json::Error 转换为 BaseError
266impl From<serde_json::Error> for BaseError {
267    fn from(err: serde_json::Error) -> Self {
268        if err.is_syntax() || err.is_data() || err.is_eof() {
269            BaseError::JsonDeserializeFailed(err.to_string())
270        } else {
271            BaseError::JsonSerializeFailed(err.to_string())
272        }
273    }
274}
275
276/// 从 reqwest::Error 转换为 BaseError
277impl From<reqwest::Error> for BaseError {
278    fn from(err: reqwest::Error) -> Self {
279        if err.is_timeout() {
280            BaseError::HttpTimeout
281        } else if err.is_connect() {
282            BaseError::HttpClientCreateFailed(err.to_string())
283        } else {
284            BaseError::HttpRequestFailed(err.to_string())
285        }
286    }
287}
288
289impl BaseError {
290    /// 获取错误码
291    ///
292    /// 返回与错误类型对应的数字错误码,用于 API 响应
293    ///
294    /// # 错误码规范
295    ///
296    /// - 1xxxxx: 插件管理错误
297    /// - 2xxxxx: 数据库错误
298    /// - 3xxxxx: HTTP 客户端错误
299    /// - 4xxxxx: Token 管理错误
300    /// - 5xxxxx: 序列化错误
301    /// - 6xxxxx: 字段验证错误
302    /// - 7xxxxx: Action 系统错误
303    /// - 9xxxxx: 通用错误
304    ///
305    /// # 返回
306    ///
307    /// - 错误码(非零整数)
308    ///
309    /// # 示例
310    ///
311    /// ```rust,ignore
312    /// use yang_base::error::BaseError;
313    ///
314    /// let error = BaseError::FieldRequired("username".to_string());
315    /// assert_eq!(error.code(), 600006);
316    /// ```
317    pub fn code(&self) -> i32 {
318        match self {
319            // ==================== 插件管理错误 (1xxxxx) ====================
320            BaseError::PluginAlreadyRegistered(_) => 100001,
321            BaseError::PluginNotFound(_) => 100002,
322            BaseError::PluginRegisterFailed(_, _) => 100003,
323            BaseError::PluginInitFailed(_, _) => 100004,
324            BaseError::PluginDependencyMissing(_, _) => 100005,
325            BaseError::PluginCircularDependency(_) => 100006,
326            BaseError::PluginConfigInvalid(_, _) => 100007,
327            BaseError::PluginShutdownFailed(_, _) => 100008,
328
329            // ==================== 数据库错误 (2xxxxx) ====================
330            BaseError::DatabaseConnectionFailed(_) => 200001,
331            BaseError::DatabaseAlreadyInitialized => 200002,
332            BaseError::DatabaseQueryFailed(_) => 200003,
333            BaseError::DatabaseExecuteFailed(_) => 200004,
334            BaseError::DatabaseInitFailed(_) => 200005,
335            BaseError::DatabaseMigrationFailed(_, _) => 200006,
336            BaseError::MigrationFailed(_, _, _) => 200007,
337            BaseError::DatabaseNotInitialized => 200008,
338            BaseError::DatabaseTransactionFailed(_) => 200009,
339
340            // ==================== Redis 错误 (21xxxx) ====================
341            BaseError::RedisConnectionFailed(_) => 210001,
342            BaseError::RedisAlreadyInitialized => 210002,
343            BaseError::RedisNotInitialized => 210003,
344            BaseError::RedisOperationFailed(_) => 210004,
345
346            // ==================== HTTP 客户端错误 (3xxxxx) ====================
347            BaseError::HttpClientCreateFailed(_) => 300001,
348            BaseError::HttpRequestFailed(_) => 300002,
349            BaseError::HttpResponseParseFailed(_) => 300003,
350            BaseError::HttpTimeout => 300004,
351
352            // ==================== Token 管理错误 (4xxxxx) ====================
353            BaseError::TokenKeyInvalid(_) => 400001,
354            BaseError::TokenGenerateFailed(_) => 400002,
355            BaseError::TokenVerifyFailed(_) => 400003,
356            BaseError::TokenParseFailed(_) => 400004,
357            BaseError::TokenExpired => 400005,
358            BaseError::TokenTypeInvalid(_) => 400006,
359
360            // ==================== 序列化错误 (5xxxxx) ====================
361            BaseError::JsonSerializeFailed(_) => 500001,
362            BaseError::JsonDeserializeFailed(_) => 500002,
363
364            // ==================== 字段验证错误 (6xxxxx) ====================
365            BaseError::InvalidFieldType(_, _) => 600001,
366            BaseError::InvalidEnumValue(_, _) => 600002,
367            BaseError::StringTooLong(_, _, _) => 600003,
368            BaseError::InvalidJsonFormat(_, _) => 600004,
369            BaseError::ValidationFailed(_, _) => 600005,
370            BaseError::FieldRequired(_) => 600006,
371            BaseError::FieldNotFound(_, _) => 600007,
372            BaseError::FieldPermissionDenied(_, _, _) => 600008,
373
374            // ==================== Action 系统错误 (7xxxxx) ====================
375            BaseError::ActionNotFound(_) => 700001,
376            BaseError::PermissionDenied(_) => 700002,
377            BaseError::Unauthorized(_) => 700003,
378            BaseError::ParamMissing(_) => 700004,
379            BaseError::ParamInvalid(_, _) => 700005,
380            BaseError::RecordNotFound(_) => 700006,
381            BaseError::UserNotFound(_) => 700007,
382            BaseError::InvalidPassword => 700008,
383            BaseError::TableConfigNotSet => 700009,
384
385            // ==================== 通用错误 (9xxxxx) ====================
386            BaseError::ConfigError(_) => 900001,
387            BaseError::IoError(_) => 900002,
388            BaseError::Unknown(_) => 999999,
389        }
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn test_error_codes_plugin() {
399        assert_eq!(
400            BaseError::PluginAlreadyRegistered("test".to_string()).code(),
401            100001
402        );
403        assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
404        assert_eq!(
405            BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
406            100003
407        );
408        assert_eq!(
409            BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
410            100004
411        );
412        assert_eq!(
413            BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
414            100005
415        );
416        assert_eq!(
417            BaseError::PluginCircularDependency("test".to_string()).code(),
418            100006
419        );
420        assert_eq!(
421            BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
422            100007
423        );
424        assert_eq!(
425            BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
426            100008
427        );
428    }
429
430    #[test]
431    fn test_error_codes_database() {
432        assert_eq!(
433            BaseError::DatabaseConnectionFailed("reason".to_string()).code(),
434            200001
435        );
436        assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
437        assert_eq!(
438            BaseError::DatabaseQueryFailed("reason".to_string()).code(),
439            200003
440        );
441        assert_eq!(
442            BaseError::DatabaseExecuteFailed("reason".to_string()).code(),
443            200004
444        );
445        assert_eq!(
446            BaseError::DatabaseInitFailed("reason".to_string()).code(),
447            200005
448        );
449        assert_eq!(
450            BaseError::DatabaseMigrationFailed("plugin".to_string(), "reason".to_string()).code(),
451            200006
452        );
453        assert_eq!(
454            BaseError::MigrationFailed(
455                "plugin".to_string(),
456                "v1".to_string(),
457                "reason".to_string()
458            )
459            .code(),
460            200007
461        );
462        assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
463        assert_eq!(
464            BaseError::DatabaseTransactionFailed("reason".to_string()).code(),
465            200009
466        );
467    }
468
469    #[test]
470    fn test_error_codes_http() {
471        assert_eq!(
472            BaseError::HttpClientCreateFailed("reason".to_string()).code(),
473            300001
474        );
475        assert_eq!(
476            BaseError::HttpRequestFailed("reason".to_string()).code(),
477            300002
478        );
479        assert_eq!(
480            BaseError::HttpResponseParseFailed("reason".to_string()).code(),
481            300003
482        );
483        assert_eq!(BaseError::HttpTimeout.code(), 300004);
484    }
485
486    #[test]
487    fn test_error_codes_token() {
488        assert_eq!(
489            BaseError::TokenKeyInvalid("reason".to_string()).code(),
490            400001
491        );
492        assert_eq!(
493            BaseError::TokenGenerateFailed("reason".to_string()).code(),
494            400002
495        );
496        assert_eq!(
497            BaseError::TokenVerifyFailed("reason".to_string()).code(),
498            400003
499        );
500        assert_eq!(
501            BaseError::TokenParseFailed("reason".to_string()).code(),
502            400004
503        );
504        assert_eq!(BaseError::TokenExpired.code(), 400005);
505        assert_eq!(
506            BaseError::TokenTypeInvalid("reason".to_string()).code(),
507            400006
508        );
509    }
510
511    #[test]
512    fn test_error_codes_serialization() {
513        assert_eq!(
514            BaseError::JsonSerializeFailed("reason".to_string()).code(),
515            500001
516        );
517        assert_eq!(
518            BaseError::JsonDeserializeFailed("reason".to_string()).code(),
519            500002
520        );
521    }
522
523    #[test]
524    fn test_error_codes_field_validation() {
525        assert_eq!(
526            BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
527            600001
528        );
529        assert_eq!(
530            BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
531            600002
532        );
533        assert_eq!(
534            BaseError::StringTooLong("field".to_string(), 100, 50).code(),
535            600003
536        );
537        assert_eq!(
538            BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
539            600004
540        );
541        assert_eq!(
542            BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
543            600005
544        );
545        assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
546        assert_eq!(
547            BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
548            600007
549        );
550        assert_eq!(
551            BaseError::FieldPermissionDenied(
552                "table".to_string(),
553                "field".to_string(),
554                "reason".to_string()
555            )
556            .code(),
557            600008
558        );
559    }
560
561    #[test]
562    fn test_error_codes_action_system() {
563        assert_eq!(
564            BaseError::ActionNotFound("test_action".to_string()).code(),
565            700001
566        );
567        assert_eq!(
568            BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
569            700002
570        );
571        assert_eq!(
572            BaseError::Unauthorized("Token 无效".to_string()).code(),
573            700003
574        );
575        assert_eq!(
576            BaseError::ParamMissing("user_id".to_string()).code(),
577            700004
578        );
579        assert_eq!(
580            BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
581            700005
582        );
583        assert_eq!(
584            BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
585            700006
586        );
587        assert_eq!(
588            BaseError::UserNotFound("user_123".to_string()).code(),
589            700007
590        );
591        assert_eq!(BaseError::InvalidPassword.code(), 700008);
592        assert_eq!(BaseError::TableConfigNotSet.code(), 700009);
593    }
594
595    #[test]
596    fn test_error_codes_general() {
597        assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
598        assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
599        assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
600    }
601
602    #[test]
603    fn test_all_error_codes_are_nonzero() {
604        // 确保所有错误码都是非零的
605        let errors = vec![
606            BaseError::PluginNotFound("test".to_string()),
607            BaseError::DatabaseQueryFailed("test".to_string()),
608            BaseError::HttpTimeout,
609            BaseError::TokenExpired,
610            BaseError::JsonSerializeFailed("test".to_string()),
611            BaseError::FieldRequired("test".to_string()),
612            BaseError::ActionNotFound("test".to_string()),
613            BaseError::PermissionDenied("test".to_string()),
614            BaseError::Unauthorized("test".to_string()),
615            BaseError::ParamMissing("test".to_string()),
616            BaseError::RecordNotFound("test".to_string()),
617            BaseError::UserNotFound("test".to_string()),
618            BaseError::InvalidPassword,
619            BaseError::TableConfigNotSet,
620            BaseError::Unknown("test".to_string()),
621        ];
622
623        for error in errors {
624            assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
625        }
626    }
627}