1use thiserror::Error;
21
22pub type Result<T, E = BaseError> = std::result::Result<T, E>;
27
28#[derive(Debug, Error)]
36#[non_exhaustive]
37pub enum BaseError {
38 #[error("插件已注册: {0}")]
41 PluginAlreadyRegistered(String),
42
43 #[error("插件未找到: {0}")]
45 PluginNotFound(String),
46
47 #[error("插件注册失败 [{0}]: {1}")]
49 PluginRegisterFailed(String, String),
50
51 #[error("插件初始化失败 [{0}]: {1}")]
53 PluginInitFailed(String, String),
54
55 #[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
57 PluginDependencyMissing(String, String),
58
59 #[error("插件循环依赖: {0}")]
61 PluginCircularDependency(String),
62
63 #[error("插件配置无效 [{0}]: {1}")]
65 PluginConfigInvalid(String, String),
66
67 #[error("插件关闭失败 [{0}]: {1}")]
69 PluginShutdownFailed(String, String),
70
71 #[error("插件生命周期失败 [{plugin}] ({stage}): {source}")]
73 PluginLifecycleFailed {
74 plugin: String,
76 stage: crate::plugin::PluginLifecycleStage,
78 #[source]
80 source: crate::plugin::PluginError,
81 },
82
83 #[error("数据库连接失败 [DbError]: {0}")]
86 DatabaseConnectionFailed(#[source] yang_db::DbError),
87
88 #[error("数据库连接失败 [DbError]: {0}")]
93 DatabaseConnectionDbError(#[source] yang_db::DbError),
94
95 #[error("数据库已初始化")]
97 DatabaseAlreadyInitialized,
98
99 #[error("数据库查询失败: {0}")]
101 DatabaseQueryFailed(#[source] yang_db::DbError),
102
103 #[error("数据库执行失败: {0}")]
105 DatabaseExecuteFailed(#[source] yang_db::DbError),
106
107 #[error("数据库初始化失败: {0}")]
109 DatabaseInitFailed(String),
110
111 #[error("数据库迁移失败 [{0}]: {1}")]
113 DatabaseMigrationFailed(String, String),
114
115 #[error("迁移失败 [{0}] v{1}: {2}")]
117 MigrationFailed(String, String, String),
118
119 #[error("迁移执行失败 [{module}] v{version} checksum={checksum}: {source}")]
121 MigrationExecutionFailed {
122 module: String,
124 version: String,
126 checksum: String,
128 #[source]
130 source: yang_db::DbError,
131 },
132
133 #[error("迁移校验和不一致 [{module}] v{version}: expected={expected}, actual={actual:?}")]
135 MigrationChecksumMismatch {
136 module: String,
138 version: String,
140 expected: String,
142 actual: Option<String>,
144 },
145
146 #[error("迁移正在执行 [{module}] v{version}")]
148 MigrationInProgress {
149 module: String,
151 version: String,
153 },
154
155 #[error("数据库未初始化")]
157 DatabaseNotInitialized,
158
159 #[error("数据库事务失败: {0}")]
161 DatabaseTransactionFailed(#[source] yang_db::DbError),
162
163 #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
168 MissingWhereClause(String),
169
170 #[error("Redis 连接失败: {0}")]
173 RedisConnectionFailed(#[source] yang_db::DbError),
174
175 #[error("Redis 已初始化")]
177 RedisAlreadyInitialized,
178
179 #[error("Redis 未初始化")]
181 RedisNotInitialized,
182
183 #[error("Redis 操作失败: {0}")]
185 RedisOperationFailed(#[source] yang_db::DbError),
186
187 #[error("Redis 操作失败: {0}")]
189 RedisOperationDbError(#[source] yang_db::DbError),
190
191 #[cfg(feature = "http")]
194 #[error("HTTP 客户端创建失败: {0}")]
195 HttpClientCreateFailed(#[source] reqwest::Error),
196
197 #[cfg(not(feature = "http"))]
199 #[error("HTTP 客户端创建失败: {0}")]
200 HttpClientCreateFailed(String),
201
202 #[cfg(feature = "http")]
204 #[error("HTTP 请求失败: {0}")]
205 HttpRequestFailed(#[source] reqwest::Error),
206
207 #[cfg(not(feature = "http"))]
209 #[error("HTTP 请求失败: {0}")]
210 HttpRequestFailed(String),
211
212 #[error("HTTP 响应解析失败: {0}")]
214 HttpResponseParseFailed(String),
215
216 #[error("HTTP 请求超时")]
218 HttpTimeout,
219
220 #[error("HTTP 客户端已初始化")]
222 HttpClientAlreadyInitialized,
223
224 #[error("HTTP 客户端未初始化")]
226 HttpClientNotInitialized,
227
228 #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
230 HttpCircuitBreakerOpen(String),
231
232 #[error("Token 密钥无效: {0}")]
235 TokenKeyInvalid(String),
236
237 #[cfg(feature = "token")]
239 #[error("Token 生成失败: {0}")]
240 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
241
242 #[cfg(not(feature = "token"))]
244 #[error("Token 生成失败: {0}")]
245 TokenGenerateFailed(String),
246
247 #[cfg(feature = "token")]
249 #[error("Token 验证失败: {0}")]
250 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
251
252 #[cfg(not(feature = "token"))]
254 #[error("Token 验证失败: {0}")]
255 TokenVerifyFailed(String),
256
257 #[cfg(feature = "token")]
259 #[error("Token 解析失败: {0}")]
260 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
261
262 #[cfg(not(feature = "token"))]
264 #[error("Token 解析失败: {0}")]
265 TokenParseFailed(String),
266
267 #[error("Token 已过期")]
269 TokenExpired,
270
271 #[error("Token 已被撤销")]
273 TokenRevoked,
274
275 #[error("Token 类型无效: {0}")]
277 TokenTypeInvalid(String),
278
279 #[error("JSON 序列化失败: {0}")]
282 JsonSerializeFailed(String),
283
284 #[error("JSON 反序列化失败: {0}")]
286 JsonDeserializeFailed(String),
287
288 #[error("字段类型无效 [{0}]: {1}")]
291 InvalidFieldType(String, String),
292
293 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
295 InvalidEnumValue(String, String),
296
297 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
299 StringTooLong(String, usize, usize),
300
301 #[error("JSON 格式无效 [{0}]: {1}")]
303 InvalidJsonFormat(String, String),
304
305 #[error("验证失败 [{0}]: {1}")]
307 ValidationFailed(String, String),
308
309 #[error("字段必填: {0}")]
311 FieldRequired(String),
312
313 #[error("字段未找到 [表: {0}]: {1}")]
315 FieldNotFound(String, String),
316
317 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
319 FieldPermissionDenied(String, String, String),
320
321 #[error("Action 未找到: {0}")]
324 ActionNotFound(String),
325
326 #[error("权限被拒绝: {0}")]
328 PermissionDenied(String),
329
330 #[error("未授权: {0}")]
332 Unauthorized(String),
333
334 #[error("参数缺失: {0}")]
336 ParamMissing(String),
337
338 #[error("参数无效 [{0}]: {1}")]
340 ParamInvalid(String, String),
341
342 #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
344 RateLimitExceeded {
345 retry_after_seconds: u64,
347 },
348
349 #[error("记录未找到: {0}")]
351 RecordNotFound(String),
352
353 #[error("用户未找到: {0}")]
355 UserNotFound(String),
356
357 #[error("密码无效")]
359 InvalidPassword,
360
361 #[error("表定义未设置")]
363 TableDefinitionNotSet,
364
365 #[cfg(feature = "token")]
367 #[error("敏感操作需要重新认证")]
368 StepUpRequired(crate::action::StepUpChallenge),
369
370 #[error("配置错误: {0}")]
373 ConfigError(String),
374
375 #[error("IO 错误: {0}")]
377 IoError(String),
378
379 #[error("未知错误: {0}")]
381 Unknown(String),
382}
383
384#[allow(unreachable_patterns)]
396impl From<yang_db::DbError> for BaseError {
397 fn from(err: yang_db::DbError) -> Self {
398 use yang_db::DbError as D;
399 match &err {
400 D::QueryError(_)
402 | D::TableNotFound(_)
403 | D::TypeConversionError(_)
404 | D::DeserializationError(_)
405 | D::UnsupportedOperator(_)
406 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
407
408 D::ConstraintError(_)
410 | D::SqlSyntaxError(_)
411 | D::MissingWhereClause
412 | D::MissingGroupByClause
413 | D::InvalidArgument(_)
414 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
415
416 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
418
419 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
421
422 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
424
425 D::RedisCommandError(_)
427 | D::RedisPoolError(_)
428 | D::RedisTypeConversionError(_)
429 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
430
431 _ => BaseError::DatabaseQueryFailed(err),
433 }
434 }
435}
436
437impl From<std::io::Error> for BaseError {
439 fn from(err: std::io::Error) -> Self {
440 BaseError::IoError(err.to_string())
441 }
442}
443
444impl From<serde_json::Error> for BaseError {
446 fn from(err: serde_json::Error) -> Self {
447 if err.is_syntax() || err.is_data() || err.is_eof() {
448 BaseError::JsonDeserializeFailed(err.to_string())
449 } else {
450 BaseError::JsonSerializeFailed(err.to_string())
451 }
452 }
453}
454
455#[cfg(feature = "http")]
457impl From<reqwest::Error> for BaseError {
458 fn from(err: reqwest::Error) -> Self {
459 if err.is_timeout() {
460 BaseError::HttpTimeout
461 } else {
462 BaseError::HttpRequestFailed(err)
466 }
467 }
468}
469
470#[cfg(feature = "token")]
477impl From<jsonwebtoken::errors::Error> for BaseError {
478 fn from(err: jsonwebtoken::errors::Error) -> Self {
479 use jsonwebtoken::errors::ErrorKind;
480 match err.kind() {
481 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
482 ErrorKind::InvalidToken
483 | ErrorKind::InvalidSignature
484 | ErrorKind::InvalidIssuer
485 | ErrorKind::InvalidAudience
486 | ErrorKind::InvalidSubject
487 | ErrorKind::InvalidAlgorithm
488 | ErrorKind::MissingAlgorithm
489 | ErrorKind::ImmatureSignature
490 | ErrorKind::MissingRequiredClaim(_)
491 | ErrorKind::InvalidEcdsaKey
492 | ErrorKind::InvalidRsaKey(_)
493 | ErrorKind::InvalidKeyFormat
494 | ErrorKind::RsaFailedSigning
495 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
496 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
498 BaseError::TokenParseFailed(err)
499 }
500 _ => BaseError::TokenVerifyFailed(err),
502 }
503 }
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514#[non_exhaustive]
515pub enum ErrorCategory {
516 Client,
518 Auth,
520 NotFound,
522 Conflict,
524 Transient,
529 Server,
531}
532
533impl BaseError {
534 pub fn code(&self) -> i32 {
563 match self {
564 BaseError::PluginAlreadyRegistered(_) => 100001,
566 BaseError::PluginNotFound(_) => 100002,
567 BaseError::PluginRegisterFailed(_, _) => 100003,
568 BaseError::PluginInitFailed(_, _) => 100004,
569 BaseError::PluginDependencyMissing(_, _) => 100005,
570 BaseError::PluginCircularDependency(_) => 100006,
571 BaseError::PluginConfigInvalid(_, _) => 100007,
572 BaseError::PluginShutdownFailed(_, _) => 100008,
573 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
574 crate::plugin::PluginLifecycleStage::Register => 100003,
575 crate::plugin::PluginLifecycleStage::Initialize => 100004,
576 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
577 },
578
579 BaseError::DatabaseConnectionFailed(_) => 200001,
581 BaseError::DatabaseConnectionDbError(_) => 200011,
582 BaseError::DatabaseAlreadyInitialized => 200002,
583 BaseError::DatabaseQueryFailed(_) => 200003,
584 BaseError::DatabaseExecuteFailed(_) => 200004,
585 BaseError::DatabaseInitFailed(_) => 200005,
586 BaseError::DatabaseMigrationFailed(_, _) => 200006,
587 BaseError::MigrationFailed(_, _, _) => 200007,
588 BaseError::MigrationExecutionFailed { .. }
589 | BaseError::MigrationChecksumMismatch { .. }
590 | BaseError::MigrationInProgress { .. } => 200007,
591 BaseError::DatabaseNotInitialized => 200008,
592 BaseError::DatabaseTransactionFailed(_) => 200009,
593 BaseError::MissingWhereClause(_) => 200010,
594
595 BaseError::RedisConnectionFailed(_) => 210001,
597 BaseError::RedisAlreadyInitialized => 210002,
598 BaseError::RedisNotInitialized => 210003,
599 BaseError::RedisOperationFailed(_) => 210004,
600 BaseError::RedisOperationDbError(_) => 210011,
601
602 BaseError::HttpClientCreateFailed(_) => 300001,
604 BaseError::HttpRequestFailed(_) => 300002,
605 BaseError::HttpResponseParseFailed(_) => 300003,
606 BaseError::HttpTimeout => 300004,
607 BaseError::HttpClientAlreadyInitialized => 300005,
608 BaseError::HttpClientNotInitialized => 300006,
609 BaseError::HttpCircuitBreakerOpen(_) => 300007,
610
611 BaseError::TokenKeyInvalid(_) => 400001,
613 BaseError::TokenGenerateFailed(_) => 400002,
614 BaseError::TokenVerifyFailed(_) => 400003,
615 BaseError::TokenParseFailed(_) => 400004,
616 BaseError::TokenExpired => 400005,
617 BaseError::TokenTypeInvalid(_) => 400006,
618 BaseError::TokenRevoked => 400007,
619
620 BaseError::JsonSerializeFailed(_) => 500001,
622 BaseError::JsonDeserializeFailed(_) => 500002,
623
624 BaseError::InvalidFieldType(_, _) => 600001,
626 BaseError::InvalidEnumValue(_, _) => 600002,
627 BaseError::StringTooLong(_, _, _) => 600003,
628 BaseError::InvalidJsonFormat(_, _) => 600004,
629 BaseError::ValidationFailed(_, _) => 600005,
630 BaseError::FieldRequired(_) => 600006,
631 BaseError::FieldNotFound(_, _) => 600007,
632 BaseError::FieldPermissionDenied(_, _, _) => 600008,
633
634 BaseError::ActionNotFound(_) => 700001,
636 BaseError::PermissionDenied(_) => 700002,
637 BaseError::Unauthorized(_) => 700003,
638 BaseError::ParamMissing(_) => 700004,
639 BaseError::ParamInvalid(_, _) => 700005,
640 BaseError::RecordNotFound(_) => 700006,
641 BaseError::UserNotFound(_) => 700007,
642 BaseError::InvalidPassword => 700008,
643 BaseError::TableDefinitionNotSet => 700009,
644 #[cfg(feature = "token")]
645 BaseError::StepUpRequired(_) => 700010,
646 BaseError::RateLimitExceeded { .. } => 700011,
647
648 BaseError::ConfigError(_) => 900001,
650 BaseError::IoError(_) => 900002,
651 BaseError::Unknown(_) => 999999,
652 }
653 }
654
655 pub fn code_str(&self) -> &'static str {
662 match self {
663 BaseError::PluginAlreadyRegistered(_) => "100001",
665 BaseError::PluginNotFound(_) => "100002",
666 BaseError::PluginRegisterFailed(_, _) => "100003",
667 BaseError::PluginInitFailed(_, _) => "100004",
668 BaseError::PluginDependencyMissing(_, _) => "100005",
669 BaseError::PluginCircularDependency(_) => "100006",
670 BaseError::PluginConfigInvalid(_, _) => "100007",
671 BaseError::PluginShutdownFailed(_, _) => "100008",
672 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
673 crate::plugin::PluginLifecycleStage::Register => "100003",
674 crate::plugin::PluginLifecycleStage::Initialize => "100004",
675 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
676 },
677 BaseError::DatabaseConnectionFailed(_) => "200001",
679 BaseError::DatabaseConnectionDbError(_) => "200011",
680 BaseError::DatabaseAlreadyInitialized => "200002",
681 BaseError::DatabaseQueryFailed(_) => "200003",
682 BaseError::DatabaseExecuteFailed(_) => "200004",
683 BaseError::DatabaseInitFailed(_) => "200005",
684 BaseError::DatabaseMigrationFailed(_, _) => "200006",
685 BaseError::MigrationFailed(_, _, _) => "200007",
686 BaseError::MigrationExecutionFailed { .. }
687 | BaseError::MigrationChecksumMismatch { .. }
688 | BaseError::MigrationInProgress { .. } => "200007",
689 BaseError::DatabaseNotInitialized => "200008",
690 BaseError::DatabaseTransactionFailed(_) => "200009",
691 BaseError::MissingWhereClause(_) => "200010",
692 BaseError::RedisConnectionFailed(_) => "210001",
694 BaseError::RedisAlreadyInitialized => "210002",
695 BaseError::RedisNotInitialized => "210003",
696 BaseError::RedisOperationFailed(_) => "210004",
697 BaseError::RedisOperationDbError(_) => "210011",
698 BaseError::HttpClientCreateFailed(_) => "300001",
700 BaseError::HttpRequestFailed(_) => "300002",
701 BaseError::HttpResponseParseFailed(_) => "300003",
702 BaseError::HttpTimeout => "300004",
703 BaseError::HttpClientAlreadyInitialized => "300005",
704 BaseError::HttpClientNotInitialized => "300006",
705 BaseError::HttpCircuitBreakerOpen(_) => "300007",
706 BaseError::TokenKeyInvalid(_) => "400001",
708 BaseError::TokenGenerateFailed(_) => "400002",
709 BaseError::TokenVerifyFailed(_) => "400003",
710 BaseError::TokenParseFailed(_) => "400004",
711 BaseError::TokenExpired => "400005",
712 BaseError::TokenTypeInvalid(_) => "400006",
713 BaseError::TokenRevoked => "400007",
714 BaseError::JsonSerializeFailed(_) => "500001",
716 BaseError::JsonDeserializeFailed(_) => "500002",
717 BaseError::InvalidFieldType(_, _) => "600001",
719 BaseError::InvalidEnumValue(_, _) => "600002",
720 BaseError::StringTooLong(_, _, _) => "600003",
721 BaseError::InvalidJsonFormat(_, _) => "600004",
722 BaseError::ValidationFailed(_, _) => "600005",
723 BaseError::FieldRequired(_) => "600006",
724 BaseError::FieldNotFound(_, _) => "600007",
725 BaseError::FieldPermissionDenied(_, _, _) => "600008",
726 BaseError::ActionNotFound(_) => "700001",
728 BaseError::PermissionDenied(_) => "700002",
729 BaseError::Unauthorized(_) => "700003",
730 BaseError::ParamMissing(_) => "700004",
731 BaseError::ParamInvalid(_, _) => "700005",
732 BaseError::RecordNotFound(_) => "700006",
733 BaseError::UserNotFound(_) => "700007",
734 BaseError::InvalidPassword => "700008",
735 BaseError::TableDefinitionNotSet => "700009",
736 #[cfg(feature = "token")]
737 BaseError::StepUpRequired(_) => "700010",
738 BaseError::RateLimitExceeded { .. } => "700011",
739 BaseError::ConfigError(_) => "900001",
741 BaseError::IoError(_) => "900002",
742 BaseError::Unknown(_) => "999999",
743 }
744 }
745
746 pub fn category(&self) -> ErrorCategory {
756 use ErrorCategory as C;
757 match self {
758 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
760 BaseError::PluginCircularDependency(_) => C::Client,
761 BaseError::PluginDependencyMissing(_, _) => C::Client,
762 BaseError::PluginConfigInvalid(_, _) => C::Client,
763 BaseError::PluginNotFound(_)
764 | BaseError::PluginRegisterFailed(_, _)
765 | BaseError::PluginInitFailed(_, _)
766 | BaseError::PluginShutdownFailed(_, _)
767 | BaseError::PluginLifecycleFailed { .. } => C::Server,
768 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
771 C::Transient
772 }
773 BaseError::MissingWhereClause(_)
774 | BaseError::DatabaseMigrationFailed(_, _)
775 | BaseError::MigrationFailed(_, _, _)
776 | BaseError::MigrationExecutionFailed { .. }
777 | BaseError::MigrationChecksumMismatch { .. }
778 | BaseError::MigrationInProgress { .. } => C::Client,
779 BaseError::DatabaseAlreadyInitialized
780 | BaseError::DatabaseNotInitialized
781 | BaseError::DatabaseInitFailed(_) => C::Server,
782 BaseError::DatabaseQueryFailed(_)
784 | BaseError::DatabaseExecuteFailed(_)
785 | BaseError::DatabaseTransactionFailed(_) => C::Server,
786 BaseError::RedisConnectionFailed(_) => C::Transient,
788 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
789 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
790 match source.category() {
791 yang_db::DbErrorCategory::Transient => C::Transient,
792 yang_db::DbErrorCategory::Conflict => C::Conflict,
793 yang_db::DbErrorCategory::Client => C::Client,
794 yang_db::DbErrorCategory::NotFound => C::NotFound,
795 yang_db::DbErrorCategory::Server => C::Server,
796 _ => C::Server,
797 }
798 }
799 BaseError::HttpClientCreateFailed(_)
801 | BaseError::HttpClientNotInitialized
802 | BaseError::HttpClientAlreadyInitialized => C::Client,
803 BaseError::HttpResponseParseFailed(_) => C::Client,
805 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
806 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
808 BaseError::TokenKeyInvalid(_)
810 | BaseError::TokenGenerateFailed(_)
811 | BaseError::TokenTypeInvalid(_)
812 | BaseError::TokenParseFailed(_) => C::Client,
813 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
814 C::Auth
815 }
816 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
818 BaseError::InvalidFieldType(_, _)
820 | BaseError::InvalidEnumValue(_, _)
821 | BaseError::StringTooLong(_, _, _)
822 | BaseError::InvalidJsonFormat(_, _)
823 | BaseError::ValidationFailed(_, _)
824 | BaseError::FieldRequired(_)
825 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
826 BaseError::FieldNotFound(_, _) => C::NotFound,
827 BaseError::Unauthorized(_) | BaseError::PermissionDenied(_) => C::Auth,
829 BaseError::ParamMissing(_)
830 | BaseError::ParamInvalid(_, _)
831 | BaseError::RateLimitExceeded { .. } => C::Client,
832 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
833 BaseError::InvalidPassword => C::Auth,
834 BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
835 #[cfg(feature = "token")]
836 BaseError::StepUpRequired(_) => C::Client,
837 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
839 }
840 }
841
842 pub fn is_retryable(&self) -> bool {
844 self.category() == ErrorCategory::Transient
845 }
846
847 pub fn is_client_error(&self) -> bool {
853 matches!(
854 self.category(),
855 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
856 )
857 }
858
859 pub fn is_server_error(&self) -> bool {
865 matches!(
866 self.category(),
867 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
868 )
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
875
876 #[test]
877 fn test_error_codes_plugin() {
878 assert_eq!(
879 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
880 100001
881 );
882 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
883 assert_eq!(
884 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
885 100003
886 );
887 assert_eq!(
888 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
889 100004
890 );
891 assert_eq!(
892 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
893 100005
894 );
895 assert_eq!(
896 BaseError::PluginCircularDependency("test".to_string()).code(),
897 100006
898 );
899 assert_eq!(
900 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
901 100007
902 );
903 assert_eq!(
904 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
905 100008
906 );
907 }
908
909 #[test]
910 fn test_error_codes_database() {
911 assert_eq!(
912 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
913 "reason".to_string()
914 ))
915 .code(),
916 200001
917 );
918 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
919 assert_eq!(
920 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
921 .code(),
922 200003
923 );
924 assert_eq!(
925 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
926 .code(),
927 200004
928 );
929 assert_eq!(
930 BaseError::DatabaseInitFailed("reason".to_string()).code(),
931 200005
932 );
933 assert_eq!(
934 BaseError::DatabaseMigrationFailed("plugin".to_string(), "reason".to_string()).code(),
935 200006
936 );
937 assert_eq!(
938 BaseError::MigrationFailed(
939 "plugin".to_string(),
940 "v1".to_string(),
941 "reason".to_string()
942 )
943 .code(),
944 200007
945 );
946 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
947 assert_eq!(
948 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
949 "reason".to_string()
950 ))
951 .code(),
952 200009
953 );
954 }
955
956 #[cfg(feature = "http")]
957 #[test]
958 fn test_error_codes_http() {
959 assert_eq!(
961 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
962 300003
963 );
964 assert_eq!(BaseError::HttpTimeout.code(), 300004);
965 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
966 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
967 }
968
969 #[cfg(feature = "token")]
970 #[test]
971 fn test_error_codes_token() {
972 assert_eq!(
973 BaseError::TokenKeyInvalid("reason".to_string()).code(),
974 400001
975 );
976 assert_eq!(
977 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
978 jsonwebtoken::errors::ErrorKind::InvalidToken
979 ))
980 .code(),
981 400002
982 );
983 assert_eq!(
984 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
985 jsonwebtoken::errors::ErrorKind::InvalidToken
986 ))
987 .code(),
988 400003
989 );
990 assert_eq!(
991 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
992 jsonwebtoken::errors::ErrorKind::InvalidToken
993 ))
994 .code(),
995 400004
996 );
997 assert_eq!(BaseError::TokenExpired.code(), 400005);
998 assert_eq!(
999 BaseError::TokenTypeInvalid("reason".to_string()).code(),
1000 400006
1001 );
1002 }
1003
1004 #[test]
1005 fn test_error_codes_serialization() {
1006 assert_eq!(
1007 BaseError::JsonSerializeFailed("reason".to_string()).code(),
1008 500001
1009 );
1010 assert_eq!(
1011 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
1012 500002
1013 );
1014 }
1015
1016 #[test]
1017 fn test_error_codes_field_validation() {
1018 assert_eq!(
1019 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
1020 600001
1021 );
1022 assert_eq!(
1023 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1024 600002
1025 );
1026 assert_eq!(
1027 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1028 600003
1029 );
1030 assert_eq!(
1031 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1032 600004
1033 );
1034 assert_eq!(
1035 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1036 600005
1037 );
1038 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1039 assert_eq!(
1040 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1041 600007
1042 );
1043 assert_eq!(
1044 BaseError::FieldPermissionDenied(
1045 "table".to_string(),
1046 "field".to_string(),
1047 "reason".to_string()
1048 )
1049 .code(),
1050 600008
1051 );
1052 }
1053
1054 #[test]
1055 fn test_error_codes_action_system() {
1056 assert_eq!(
1057 BaseError::ActionNotFound("test_action".to_string()).code(),
1058 700001
1059 );
1060 assert_eq!(
1061 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1062 700002
1063 );
1064 assert_eq!(
1065 BaseError::Unauthorized("Token 无效".to_string()).code(),
1066 700003
1067 );
1068 assert_eq!(
1069 BaseError::ParamMissing("user_id".to_string()).code(),
1070 700004
1071 );
1072 assert_eq!(
1073 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1074 700005
1075 );
1076 assert_eq!(
1077 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1078 700006
1079 );
1080 assert_eq!(
1081 BaseError::UserNotFound("user_123".to_string()).code(),
1082 700007
1083 );
1084 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1085 assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1086 assert_eq!(
1087 BaseError::RateLimitExceeded {
1088 retry_after_seconds: 30
1089 }
1090 .code(),
1091 700011
1092 );
1093 }
1094
1095 #[test]
1096 fn test_error_codes_general() {
1097 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1098 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1099 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1100 }
1101
1102 #[test]
1103 fn test_all_error_codes_are_nonzero() {
1104 let errors: Vec<BaseError> = vec![
1106 BaseError::PluginNotFound("test".to_string()),
1107 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1108 BaseError::HttpTimeout,
1109 BaseError::TokenExpired,
1110 BaseError::JsonSerializeFailed("test".to_string()),
1111 BaseError::FieldRequired("test".to_string()),
1112 BaseError::ActionNotFound("test".to_string()),
1113 BaseError::PermissionDenied("test".to_string()),
1114 BaseError::Unauthorized("test".to_string()),
1115 BaseError::ParamMissing("test".to_string()),
1116 BaseError::RecordNotFound("test".to_string()),
1117 BaseError::UserNotFound("test".to_string()),
1118 BaseError::InvalidPassword,
1119 BaseError::TableDefinitionNotSet,
1120 BaseError::RateLimitExceeded {
1121 retry_after_seconds: 30,
1122 },
1123 BaseError::Unknown("test".to_string()),
1124 ];
1125
1126 for error in errors {
1127 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1128 }
1129 }
1130
1131 #[test]
1133 fn test_database_error_source_chain() {
1134 use std::error::Error;
1135
1136 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1137 let base_err = BaseError::DatabaseQueryFailed(db_err);
1138
1139 let source = base_err.source();
1141 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1142 }
1143
1144 #[test]
1146 fn test_from_db_error_preserves_source() {
1147 use std::error::Error;
1148
1149 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1150 let base_err: BaseError = db_err.into();
1151
1152 assert!(base_err.source().is_some());
1154 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1155 }
1156
1157 #[test]
1158 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1159 use std::error::Error;
1160
1161 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1162 "connection refused".into(),
1163 ));
1164 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1165 "WRONGTYPE".into(),
1166 ));
1167
1168 assert_eq!(connection.code(), 210001);
1169 assert_eq!(operation.code(), 210004);
1170 assert!(connection.source().is_some());
1171 assert!(operation.source().is_some());
1172 }
1173
1174 #[test]
1175 fn test_migration_execution_error_preserves_context_and_source() {
1176 use std::error::Error;
1177
1178 let error = BaseError::MigrationExecutionFailed {
1179 module: "accounts".into(),
1180 version: "202607150001".into(),
1181 checksum: "0123456789abcdef".into(),
1182 source: yang_db::DbError::SqlSyntaxError("bad ddl".into()),
1183 };
1184
1185 assert_eq!(error.code(), 200007);
1186 assert_eq!(error.code_str(), "200007");
1187 assert!(error.to_string().contains("accounts"));
1188 assert!(error.to_string().contains("202607150001"));
1189 assert!(error.to_string().contains("0123456789abcdef"));
1190 assert!(error.source().is_some());
1191 }
1192
1193 #[test]
1194 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1195 use std::error::Error;
1196
1197 let error = BaseError::PluginLifecycleFailed {
1198 plugin: "audit".into(),
1199 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1200 source: Box::new(std::io::Error::other("flush failed")),
1201 };
1202
1203 assert_eq!(error.code(), 100008);
1204 assert_eq!(error.code_str(), "100008");
1205 assert!(error.to_string().contains("audit"));
1206 assert!(error.to_string().contains("shutdown"));
1207 assert!(error.source().is_some());
1208 }
1209
1210 #[test]
1212 fn test_code_str_matches_code() {
1213 let samples: Vec<BaseError> = vec![
1215 BaseError::PluginNotFound("p".into()),
1216 BaseError::PluginLifecycleFailed {
1217 plugin: "p".into(),
1218 stage: crate::plugin::PluginLifecycleStage::Initialize,
1219 source: Box::new(std::io::Error::other("init")),
1220 },
1221 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1222 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1223 BaseError::MigrationExecutionFailed {
1224 module: "m".into(),
1225 version: "v1".into(),
1226 checksum: "c".into(),
1227 source: yang_db::DbError::QueryError("q".into()),
1228 },
1229 BaseError::DatabaseNotInitialized,
1230 BaseError::RedisNotInitialized,
1231 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1232 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1233 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1234 BaseError::HttpTimeout,
1235 BaseError::TokenExpired,
1236 BaseError::TokenRevoked,
1237 BaseError::JsonSerializeFailed("s".into()),
1238 BaseError::FieldNotFound("t".into(), "f".into()),
1239 BaseError::ParamInvalid("k".into(), "r".into()),
1240 BaseError::TableDefinitionNotSet,
1241 BaseError::RateLimitExceeded {
1242 retry_after_seconds: 30,
1243 },
1244 BaseError::ConfigError("c".into()),
1245 BaseError::Unknown("u".into()),
1246 ];
1247 for err in samples {
1248 let code = err.code();
1249 let code_str = err.code_str();
1250 assert_eq!(
1251 code_str.parse::<i32>().unwrap(),
1252 code,
1253 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1254 code_str,
1255 code,
1256 err
1257 );
1258 }
1259 }
1260
1261 #[test]
1263 fn test_error_category_coverage() {
1264 assert_eq!(
1266 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1267 ErrorCategory::Client
1268 );
1269 assert_eq!(
1270 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1271 ErrorCategory::Client
1272 );
1273 assert_eq!(
1275 BaseError::Unauthorized("u".into()).category(),
1276 ErrorCategory::Auth
1277 );
1278 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1279 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1280 assert_eq!(
1282 BaseError::RecordNotFound("r".into()).category(),
1283 ErrorCategory::NotFound
1284 );
1285 assert_eq!(
1286 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1287 ErrorCategory::NotFound
1288 );
1289 assert_eq!(
1291 BaseError::PluginAlreadyRegistered("p".into()).category(),
1292 ErrorCategory::Conflict
1293 );
1294 assert_eq!(
1296 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1297 .category(),
1298 ErrorCategory::Transient
1299 );
1300 assert_eq!(
1301 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1302 .category(),
1303 ErrorCategory::Transient
1304 );
1305 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1306 assert_eq!(
1308 BaseError::Unknown("u".into()).category(),
1309 ErrorCategory::Server
1310 );
1311 assert_eq!(
1312 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1313 ErrorCategory::Server
1314 );
1315 }
1316
1317 #[test]
1319 fn test_is_retryable() {
1320 assert!(
1321 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1322 .is_retryable()
1323 );
1324 assert!(BaseError::HttpTimeout.is_retryable());
1325 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1326 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1327 assert!(!BaseError::Unknown("u".into()).is_retryable());
1328 }
1329
1330 #[test]
1332 fn test_is_client_error() {
1333 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1334 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1335 assert!(BaseError::TokenExpired.is_client_error());
1336 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1337 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1338 assert!(
1339 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1340 .is_client_error()
1341 );
1342 assert!(!BaseError::Unknown("u".into()).is_client_error());
1343 }
1344
1345 #[test]
1347 fn test_is_server_error() {
1348 assert!(BaseError::Unknown("u".into()).is_server_error());
1349 assert!(
1350 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1351 .is_server_error()
1352 );
1353 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1354 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1355 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1356 }
1357}