1use thiserror::Error;
21
22#[derive(Debug, Error)]
26pub enum BaseError {
27 #[error("插件已注册: {0}")]
30 PluginAlreadyRegistered(String),
31
32 #[error("插件未找到: {0}")]
34 PluginNotFound(String),
35
36 #[error("插件注册失败 [{0}]: {1}")]
38 PluginRegisterFailed(String, String),
39
40 #[error("插件初始化失败 [{0}]: {1}")]
42 PluginInitFailed(String, String),
43
44 #[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
46 PluginDependencyMissing(String, String),
47
48 #[error("插件循环依赖: {0}")]
50 PluginCircularDependency(String),
51
52 #[error("插件配置无效 [{0}]: {1}")]
54 PluginConfigInvalid(String, String),
55
56 #[error("插件关闭失败 [{0}]: {1}")]
58 PluginShutdownFailed(String, String),
59
60 #[error("数据库连接失败: {0}")]
63 DatabaseConnectionFailed(String),
64
65 #[error("数据库已初始化")]
67 DatabaseAlreadyInitialized,
68
69 #[error("数据库查询失败: {0}")]
71 DatabaseQueryFailed(#[source] yang_db::DbError),
72
73 #[error("数据库执行失败: {0}")]
75 DatabaseExecuteFailed(#[source] yang_db::DbError),
76
77 #[error("数据库初始化失败: {0}")]
79 DatabaseInitFailed(String),
80
81 #[error("数据库迁移失败 [{0}]: {1}")]
83 DatabaseMigrationFailed(String, String),
84
85 #[error("迁移失败 [{0}] v{1}: {2}")]
87 MigrationFailed(String, String, String),
88
89 #[error("数据库未初始化")]
91 DatabaseNotInitialized,
92
93 #[error("数据库事务失败: {0}")]
95 DatabaseTransactionFailed(#[source] yang_db::DbError),
96
97 #[error("Redis 连接失败: {0}")]
100 RedisConnectionFailed(String),
101
102 #[error("Redis 已初始化")]
104 RedisAlreadyInitialized,
105
106 #[error("Redis 未初始化")]
108 RedisNotInitialized,
109
110 #[error("Redis 操作失败: {0}")]
112 RedisOperationFailed(String),
113
114 #[cfg(feature = "http")]
117 #[error("HTTP 客户端创建失败: {0}")]
118 HttpClientCreateFailed(#[source] reqwest::Error),
119
120 #[cfg(not(feature = "http"))]
122 #[error("HTTP 客户端创建失败: {0}")]
123 HttpClientCreateFailed(String),
124
125 #[cfg(feature = "http")]
127 #[error("HTTP 请求失败: {0}")]
128 HttpRequestFailed(#[source] reqwest::Error),
129
130 #[cfg(not(feature = "http"))]
132 #[error("HTTP 请求失败: {0}")]
133 HttpRequestFailed(String),
134
135 #[error("HTTP 响应解析失败: {0}")]
137 HttpResponseParseFailed(String),
138
139 #[error("HTTP 请求超时")]
141 HttpTimeout,
142
143 #[error("HTTP 客户端已初始化")]
145 HttpClientAlreadyInitialized,
146
147 #[error("HTTP 客户端未初始化")]
149 HttpClientNotInitialized,
150
151 #[error("Token 密钥无效: {0}")]
154 TokenKeyInvalid(String),
155
156 #[cfg(feature = "token")]
158 #[error("Token 生成失败: {0}")]
159 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
160
161 #[cfg(not(feature = "token"))]
163 #[error("Token 生成失败: {0}")]
164 TokenGenerateFailed(String),
165
166 #[cfg(feature = "token")]
168 #[error("Token 验证失败: {0}")]
169 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
170
171 #[cfg(not(feature = "token"))]
173 #[error("Token 验证失败: {0}")]
174 TokenVerifyFailed(String),
175
176 #[cfg(feature = "token")]
178 #[error("Token 解析失败: {0}")]
179 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
180
181 #[cfg(not(feature = "token"))]
183 #[error("Token 解析失败: {0}")]
184 TokenParseFailed(String),
185
186 #[error("Token 已过期")]
188 TokenExpired,
189
190 #[error("Token 类型无效: {0}")]
192 TokenTypeInvalid(String),
193
194 #[error("JSON 序列化失败: {0}")]
197 JsonSerializeFailed(String),
198
199 #[error("JSON 反序列化失败: {0}")]
201 JsonDeserializeFailed(String),
202
203 #[error("字段类型无效 [{0}]: {1}")]
206 InvalidFieldType(String, String),
207
208 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
210 InvalidEnumValue(String, String),
211
212 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
214 StringTooLong(String, usize, usize),
215
216 #[error("JSON 格式无效 [{0}]: {1}")]
218 InvalidJsonFormat(String, String),
219
220 #[error("验证失败 [{0}]: {1}")]
222 ValidationFailed(String, String),
223
224 #[error("字段必填: {0}")]
226 FieldRequired(String),
227
228 #[error("字段未找到 [表: {0}]: {1}")]
230 FieldNotFound(String, String),
231
232 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
234 FieldPermissionDenied(String, String, String),
235
236 #[error("Action 未找到: {0}")]
239 ActionNotFound(String),
240
241 #[error("权限被拒绝: {0}")]
243 PermissionDenied(String),
244
245 #[error("未授权: {0}")]
247 Unauthorized(String),
248
249 #[error("参数缺失: {0}")]
251 ParamMissing(String),
252
253 #[error("参数无效 [{0}]: {1}")]
255 ParamInvalid(String, String),
256
257 #[error("记录未找到: {0}")]
259 RecordNotFound(String),
260
261 #[error("用户未找到: {0}")]
263 UserNotFound(String),
264
265 #[error("密码无效")]
267 InvalidPassword,
268
269 #[error("表配置未设置")]
271 TableConfigNotSet,
272
273 #[error("配置错误: {0}")]
276 ConfigError(String),
277
278 #[error("IO 错误: {0}")]
280 IoError(String),
281
282 #[error("未知错误: {0}")]
284 Unknown(String),
285}
286
287impl 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 D::QueryError(_)
303 | D::TableNotFound(_)
304 | D::TypeConversionError(_)
305 | D::DeserializationError(_)
306 | D::UnsupportedOperator(_)
307 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
308
309 D::ConstraintError(_)
311 | D::SqlSyntaxError(_)
312 | D::MissingWhereClause
313 | D::MissingGroupByClause
314 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
315
316 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
318
319 D::ConnectionError(_) => BaseError::DatabaseConnectionFailed(err.to_string()),
321
322 D::RedisConnectionError(_)
324 | D::RedisCommandError(_)
325 | D::RedisPoolError(_)
326 | D::RedisTypeConversionError(_)
327 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err.to_string()),
328 }
329 }
330}
331
332impl From<std::io::Error> for BaseError {
334 fn from(err: std::io::Error) -> Self {
335 BaseError::IoError(err.to_string())
336 }
337}
338
339impl 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#[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#[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 pub fn code(&self) -> i32 {
413 match self {
414 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 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 BaseError::RedisConnectionFailed(_) => 210001,
437 BaseError::RedisAlreadyInitialized => 210002,
438 BaseError::RedisNotInitialized => 210003,
439 BaseError::RedisOperationFailed(_) => 210004,
440
441 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 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 BaseError::JsonSerializeFailed(_) => 500001,
459 BaseError::JsonDeserializeFailed(_) => 500002,
460
461 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 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 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 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 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 #[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 let source = base_err.source();
746 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
747 }
748
749 #[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 assert!(base_err.source().is_some());
759 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
760 }
761}