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("数据库未初始化")]
113 DatabaseNotInitialized,
114
115 #[error("数据库事务失败: {0}")]
117 DatabaseTransactionFailed(#[source] yang_db::DbError),
118
119 #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
124 MissingWhereClause(String),
125
126 #[error("Redis 连接失败: {0}")]
129 RedisConnectionFailed(#[source] yang_db::DbError),
130
131 #[error("Redis 已初始化")]
133 RedisAlreadyInitialized,
134
135 #[error("Redis 未初始化")]
137 RedisNotInitialized,
138
139 #[error("Redis 操作失败: {0}")]
141 RedisOperationFailed(#[source] yang_db::DbError),
142
143 #[error("Redis 操作失败: {0}")]
145 RedisOperationDbError(#[source] yang_db::DbError),
146
147 #[cfg(feature = "http")]
150 #[error("HTTP 客户端创建失败: {0}")]
151 HttpClientCreateFailed(#[source] reqwest::Error),
152
153 #[cfg(not(feature = "http"))]
155 #[error("HTTP 客户端创建失败: {0}")]
156 HttpClientCreateFailed(String),
157
158 #[cfg(feature = "http")]
160 #[error("HTTP 请求失败: {0}")]
161 HttpRequestFailed(#[source] reqwest::Error),
162
163 #[cfg(not(feature = "http"))]
165 #[error("HTTP 请求失败: {0}")]
166 HttpRequestFailed(String),
167
168 #[error("HTTP 响应解析失败: {0}")]
170 HttpResponseParseFailed(String),
171
172 #[error("HTTP 请求超时")]
174 HttpTimeout,
175
176 #[error("HTTP 客户端已初始化")]
178 HttpClientAlreadyInitialized,
179
180 #[error("HTTP 客户端未初始化")]
182 HttpClientNotInitialized,
183
184 #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
186 HttpCircuitBreakerOpen(String),
187
188 #[error("Token 密钥无效: {0}")]
191 TokenKeyInvalid(String),
192
193 #[cfg(feature = "token")]
195 #[error("Token 生成失败: {0}")]
196 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
197
198 #[cfg(not(feature = "token"))]
200 #[error("Token 生成失败: {0}")]
201 TokenGenerateFailed(String),
202
203 #[cfg(feature = "token")]
205 #[error("Token 验证失败: {0}")]
206 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
207
208 #[cfg(not(feature = "token"))]
210 #[error("Token 验证失败: {0}")]
211 TokenVerifyFailed(String),
212
213 #[cfg(feature = "token")]
215 #[error("Token 解析失败: {0}")]
216 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
217
218 #[cfg(not(feature = "token"))]
220 #[error("Token 解析失败: {0}")]
221 TokenParseFailed(String),
222
223 #[error("Token 已过期")]
225 TokenExpired,
226
227 #[error("Token 已被撤销")]
229 TokenRevoked,
230
231 #[error("Token 撤销状态无效: {0}")]
233 TokenRevocationStateInvalid(String),
234
235 #[error("授权状态已变更,请刷新登录")]
237 AuthorizationStale,
238
239 #[error("授权版本无效")]
241 AuthorizationVersionInvalid,
242
243 #[error("授权状态暂时无法校验")]
245 AuthorizationCheckUnavailable,
246
247 #[error("Token 类型无效: {0}")]
249 TokenTypeInvalid(String),
250
251 #[error("JSON 序列化失败: {0}")]
254 JsonSerializeFailed(String),
255
256 #[error("JSON 反序列化失败: {0}")]
258 JsonDeserializeFailed(String),
259
260 #[error("字段类型无效 [{0}]: {1}")]
263 InvalidFieldType(String, String),
264
265 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
267 InvalidEnumValue(String, String),
268
269 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
271 StringTooLong(String, usize, usize),
272
273 #[error("JSON 格式无效 [{0}]: {1}")]
275 InvalidJsonFormat(String, String),
276
277 #[error("验证失败 [{0}]: {1}")]
279 ValidationFailed(String, String),
280
281 #[error("字段必填: {0}")]
283 FieldRequired(String),
284
285 #[error("字段未找到 [表: {0}]: {1}")]
287 FieldNotFound(String, String),
288
289 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
291 FieldPermissionDenied(String, String, String),
292
293 #[error("Action 未找到: {0}")]
296 ActionNotFound(String),
297
298 #[error("权限被拒绝: {0}")]
300 PermissionDenied(String),
301
302 #[error("未授权: {0}")]
304 Unauthorized(String),
305
306 #[error("参数缺失: {0}")]
308 ParamMissing(String),
309
310 #[error("参数无效 [{0}]: {1}")]
312 ParamInvalid(String, String),
313
314 #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
316 RateLimitExceeded {
317 retry_after_seconds: u64,
319 },
320
321 #[error("记录未找到: {0}")]
323 RecordNotFound(String),
324
325 #[error("用户未找到: {0}")]
327 UserNotFound(String),
328
329 #[error("密码无效")]
331 InvalidPassword,
332
333 #[error("表定义未设置")]
335 TableDefinitionNotSet,
336
337 #[cfg(feature = "token")]
339 #[error("敏感操作需要重新认证")]
340 StepUpRequired(crate::action::StepUpChallenge),
341
342 #[error("配置错误: {0}")]
345 ConfigError(String),
346
347 #[error("IO 错误: {0}")]
349 IoError(String),
350
351 #[error("未知错误: {0}")]
353 Unknown(String),
354}
355
356#[allow(unreachable_patterns)]
368impl From<yang_db::DbError> for BaseError {
369 fn from(err: yang_db::DbError) -> Self {
370 use yang_db::DbError as D;
371 match &err {
372 D::QueryError(_)
374 | D::TableNotFound(_)
375 | D::TypeConversionError(_)
376 | D::DeserializationError(_)
377 | D::UnsupportedOperator(_)
378 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
379
380 D::ConstraintError(_)
382 | D::SqlSyntaxError(_)
383 | D::MissingWhereClause
384 | D::MissingGroupByClause
385 | D::InvalidArgument(_)
386 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
387
388 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
390
391 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
393
394 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
396
397 D::RedisCommandError(_)
399 | D::RedisPoolError(_)
400 | D::RedisTypeConversionError(_)
401 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
402
403 _ => BaseError::DatabaseQueryFailed(err),
405 }
406 }
407}
408
409impl From<std::io::Error> for BaseError {
411 fn from(err: std::io::Error) -> Self {
412 BaseError::IoError(err.to_string())
413 }
414}
415
416impl From<serde_json::Error> for BaseError {
418 fn from(err: serde_json::Error) -> Self {
419 if err.is_syntax() || err.is_data() || err.is_eof() {
420 BaseError::JsonDeserializeFailed(err.to_string())
421 } else {
422 BaseError::JsonSerializeFailed(err.to_string())
423 }
424 }
425}
426
427#[cfg(feature = "http")]
429impl From<reqwest::Error> for BaseError {
430 fn from(err: reqwest::Error) -> Self {
431 if err.is_timeout() {
432 BaseError::HttpTimeout
433 } else {
434 BaseError::HttpRequestFailed(err)
438 }
439 }
440}
441
442#[cfg(feature = "token")]
449impl From<jsonwebtoken::errors::Error> for BaseError {
450 fn from(err: jsonwebtoken::errors::Error) -> Self {
451 use jsonwebtoken::errors::ErrorKind;
452 match err.kind() {
453 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
454 ErrorKind::InvalidToken
455 | ErrorKind::InvalidSignature
456 | ErrorKind::InvalidIssuer
457 | ErrorKind::InvalidAudience
458 | ErrorKind::InvalidSubject
459 | ErrorKind::InvalidAlgorithm
460 | ErrorKind::MissingAlgorithm
461 | ErrorKind::ImmatureSignature
462 | ErrorKind::MissingRequiredClaim(_)
463 | ErrorKind::InvalidEcdsaKey
464 | ErrorKind::InvalidRsaKey(_)
465 | ErrorKind::InvalidKeyFormat
466 | ErrorKind::RsaFailedSigning
467 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
468 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
470 BaseError::TokenParseFailed(err)
471 }
472 _ => BaseError::TokenVerifyFailed(err),
474 }
475 }
476}
477
478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486#[non_exhaustive]
487pub enum ErrorCategory {
488 Client,
490 Auth,
492 NotFound,
494 Conflict,
496 Transient,
501 Server,
503}
504
505impl BaseError {
506 pub fn code(&self) -> i32 {
535 match self {
536 BaseError::PluginAlreadyRegistered(_) => 100001,
538 BaseError::PluginNotFound(_) => 100002,
539 BaseError::PluginRegisterFailed(_, _) => 100003,
540 BaseError::PluginInitFailed(_, _) => 100004,
541 BaseError::PluginDependencyMissing(_, _) => 100005,
542 BaseError::PluginCircularDependency(_) => 100006,
543 BaseError::PluginConfigInvalid(_, _) => 100007,
544 BaseError::PluginShutdownFailed(_, _) => 100008,
545 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
546 crate::plugin::PluginLifecycleStage::Register => 100003,
547 crate::plugin::PluginLifecycleStage::Initialize => 100004,
548 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
549 },
550
551 BaseError::DatabaseConnectionFailed(_) => 200001,
553 BaseError::DatabaseConnectionDbError(_) => 200011,
554 BaseError::DatabaseAlreadyInitialized => 200002,
555 BaseError::DatabaseQueryFailed(_) => 200003,
556 BaseError::DatabaseExecuteFailed(_) => 200004,
557 BaseError::DatabaseInitFailed(_) => 200005,
558 BaseError::DatabaseNotInitialized => 200008,
559 BaseError::DatabaseTransactionFailed(_) => 200009,
560 BaseError::MissingWhereClause(_) => 200010,
561
562 BaseError::RedisConnectionFailed(_) => 210001,
564 BaseError::RedisAlreadyInitialized => 210002,
565 BaseError::RedisNotInitialized => 210003,
566 BaseError::RedisOperationFailed(_) => 210004,
567 BaseError::RedisOperationDbError(_) => 210011,
568
569 BaseError::HttpClientCreateFailed(_) => 300001,
571 BaseError::HttpRequestFailed(_) => 300002,
572 BaseError::HttpResponseParseFailed(_) => 300003,
573 BaseError::HttpTimeout => 300004,
574 BaseError::HttpClientAlreadyInitialized => 300005,
575 BaseError::HttpClientNotInitialized => 300006,
576 BaseError::HttpCircuitBreakerOpen(_) => 300007,
577
578 BaseError::TokenKeyInvalid(_) => 400001,
580 BaseError::TokenGenerateFailed(_) => 400002,
581 BaseError::TokenVerifyFailed(_) => 400003,
582 BaseError::TokenParseFailed(_) => 400004,
583 BaseError::TokenExpired => 400005,
584 BaseError::TokenTypeInvalid(_) => 400006,
585 BaseError::TokenRevoked => 400007,
586 BaseError::TokenRevocationStateInvalid(_) => 400008,
587 BaseError::AuthorizationStale => 400009,
588 BaseError::AuthorizationVersionInvalid => 400010,
589 BaseError::AuthorizationCheckUnavailable => 400011,
590
591 BaseError::JsonSerializeFailed(_) => 500001,
593 BaseError::JsonDeserializeFailed(_) => 500002,
594
595 BaseError::InvalidFieldType(_, _) => 600001,
597 BaseError::InvalidEnumValue(_, _) => 600002,
598 BaseError::StringTooLong(_, _, _) => 600003,
599 BaseError::InvalidJsonFormat(_, _) => 600004,
600 BaseError::ValidationFailed(_, _) => 600005,
601 BaseError::FieldRequired(_) => 600006,
602 BaseError::FieldNotFound(_, _) => 600007,
603 BaseError::FieldPermissionDenied(_, _, _) => 600008,
604
605 BaseError::ActionNotFound(_) => 700001,
607 BaseError::PermissionDenied(_) => 700002,
608 BaseError::Unauthorized(_) => 700003,
609 BaseError::ParamMissing(_) => 700004,
610 BaseError::ParamInvalid(_, _) => 700005,
611 BaseError::RecordNotFound(_) => 700006,
612 BaseError::UserNotFound(_) => 700007,
613 BaseError::InvalidPassword => 700008,
614 BaseError::TableDefinitionNotSet => 700009,
615 #[cfg(feature = "token")]
616 BaseError::StepUpRequired(_) => 700010,
617 BaseError::RateLimitExceeded { .. } => 700011,
618
619 BaseError::ConfigError(_) => 900001,
621 BaseError::IoError(_) => 900002,
622 BaseError::Unknown(_) => 999999,
623 }
624 }
625
626 pub fn code_str(&self) -> &'static str {
633 match self {
634 BaseError::PluginAlreadyRegistered(_) => "100001",
636 BaseError::PluginNotFound(_) => "100002",
637 BaseError::PluginRegisterFailed(_, _) => "100003",
638 BaseError::PluginInitFailed(_, _) => "100004",
639 BaseError::PluginDependencyMissing(_, _) => "100005",
640 BaseError::PluginCircularDependency(_) => "100006",
641 BaseError::PluginConfigInvalid(_, _) => "100007",
642 BaseError::PluginShutdownFailed(_, _) => "100008",
643 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
644 crate::plugin::PluginLifecycleStage::Register => "100003",
645 crate::plugin::PluginLifecycleStage::Initialize => "100004",
646 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
647 },
648 BaseError::DatabaseConnectionFailed(_) => "200001",
650 BaseError::DatabaseConnectionDbError(_) => "200011",
651 BaseError::DatabaseAlreadyInitialized => "200002",
652 BaseError::DatabaseQueryFailed(_) => "200003",
653 BaseError::DatabaseExecuteFailed(_) => "200004",
654 BaseError::DatabaseInitFailed(_) => "200005",
655 BaseError::DatabaseNotInitialized => "200008",
656 BaseError::DatabaseTransactionFailed(_) => "200009",
657 BaseError::MissingWhereClause(_) => "200010",
658 BaseError::RedisConnectionFailed(_) => "210001",
660 BaseError::RedisAlreadyInitialized => "210002",
661 BaseError::RedisNotInitialized => "210003",
662 BaseError::RedisOperationFailed(_) => "210004",
663 BaseError::RedisOperationDbError(_) => "210011",
664 BaseError::HttpClientCreateFailed(_) => "300001",
666 BaseError::HttpRequestFailed(_) => "300002",
667 BaseError::HttpResponseParseFailed(_) => "300003",
668 BaseError::HttpTimeout => "300004",
669 BaseError::HttpClientAlreadyInitialized => "300005",
670 BaseError::HttpClientNotInitialized => "300006",
671 BaseError::HttpCircuitBreakerOpen(_) => "300007",
672 BaseError::TokenKeyInvalid(_) => "400001",
674 BaseError::TokenGenerateFailed(_) => "400002",
675 BaseError::TokenVerifyFailed(_) => "400003",
676 BaseError::TokenParseFailed(_) => "400004",
677 BaseError::TokenExpired => "400005",
678 BaseError::TokenTypeInvalid(_) => "400006",
679 BaseError::TokenRevoked => "400007",
680 BaseError::TokenRevocationStateInvalid(_) => "400008",
681 BaseError::AuthorizationStale => "400009",
682 BaseError::AuthorizationVersionInvalid => "400010",
683 BaseError::AuthorizationCheckUnavailable => "400011",
684 BaseError::JsonSerializeFailed(_) => "500001",
686 BaseError::JsonDeserializeFailed(_) => "500002",
687 BaseError::InvalidFieldType(_, _) => "600001",
689 BaseError::InvalidEnumValue(_, _) => "600002",
690 BaseError::StringTooLong(_, _, _) => "600003",
691 BaseError::InvalidJsonFormat(_, _) => "600004",
692 BaseError::ValidationFailed(_, _) => "600005",
693 BaseError::FieldRequired(_) => "600006",
694 BaseError::FieldNotFound(_, _) => "600007",
695 BaseError::FieldPermissionDenied(_, _, _) => "600008",
696 BaseError::ActionNotFound(_) => "700001",
698 BaseError::PermissionDenied(_) => "700002",
699 BaseError::Unauthorized(_) => "700003",
700 BaseError::ParamMissing(_) => "700004",
701 BaseError::ParamInvalid(_, _) => "700005",
702 BaseError::RecordNotFound(_) => "700006",
703 BaseError::UserNotFound(_) => "700007",
704 BaseError::InvalidPassword => "700008",
705 BaseError::TableDefinitionNotSet => "700009",
706 #[cfg(feature = "token")]
707 BaseError::StepUpRequired(_) => "700010",
708 BaseError::RateLimitExceeded { .. } => "700011",
709 BaseError::ConfigError(_) => "900001",
711 BaseError::IoError(_) => "900002",
712 BaseError::Unknown(_) => "999999",
713 }
714 }
715
716 pub fn category(&self) -> ErrorCategory {
726 use ErrorCategory as C;
727 match self {
728 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
730 BaseError::PluginCircularDependency(_) => C::Client,
731 BaseError::PluginDependencyMissing(_, _) => C::Client,
732 BaseError::PluginConfigInvalid(_, _) => C::Client,
733 BaseError::PluginNotFound(_)
734 | BaseError::PluginRegisterFailed(_, _)
735 | BaseError::PluginInitFailed(_, _)
736 | BaseError::PluginShutdownFailed(_, _)
737 | BaseError::PluginLifecycleFailed { .. } => C::Server,
738 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
741 C::Transient
742 }
743 BaseError::MissingWhereClause(_) => C::Client,
744 BaseError::DatabaseAlreadyInitialized
745 | BaseError::DatabaseNotInitialized
746 | BaseError::DatabaseInitFailed(_) => C::Server,
747 BaseError::DatabaseQueryFailed(_)
749 | BaseError::DatabaseExecuteFailed(_)
750 | BaseError::DatabaseTransactionFailed(_) => C::Server,
751 BaseError::RedisConnectionFailed(_) => C::Transient,
753 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
754 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
755 match source.category() {
756 yang_db::DbErrorCategory::Transient => C::Transient,
757 yang_db::DbErrorCategory::Conflict => C::Conflict,
758 yang_db::DbErrorCategory::Client => C::Client,
759 yang_db::DbErrorCategory::NotFound => C::NotFound,
760 yang_db::DbErrorCategory::Server => C::Server,
761 _ => C::Server,
762 }
763 }
764 BaseError::HttpClientCreateFailed(_)
766 | BaseError::HttpClientNotInitialized
767 | BaseError::HttpClientAlreadyInitialized => C::Client,
768 BaseError::HttpResponseParseFailed(_) => C::Client,
770 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
771 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
773 BaseError::TokenKeyInvalid(_)
775 | BaseError::TokenGenerateFailed(_)
776 | BaseError::TokenTypeInvalid(_)
777 | BaseError::TokenParseFailed(_) => C::Client,
778 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
779 C::Auth
780 }
781 BaseError::TokenRevocationStateInvalid(_) => C::Server,
782 BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
783 BaseError::AuthorizationCheckUnavailable => C::Transient,
784 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
786 BaseError::InvalidFieldType(_, _)
788 | BaseError::InvalidEnumValue(_, _)
789 | BaseError::StringTooLong(_, _, _)
790 | BaseError::InvalidJsonFormat(_, _)
791 | BaseError::ValidationFailed(_, _)
792 | BaseError::FieldRequired(_)
793 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
794 BaseError::FieldNotFound(_, _) => C::NotFound,
795 BaseError::Unauthorized(_) | BaseError::PermissionDenied(_) => C::Auth,
797 BaseError::ParamMissing(_)
798 | BaseError::ParamInvalid(_, _)
799 | BaseError::RateLimitExceeded { .. } => C::Client,
800 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
801 BaseError::InvalidPassword => C::Auth,
802 BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
803 #[cfg(feature = "token")]
804 BaseError::StepUpRequired(_) => C::Client,
805 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
807 }
808 }
809
810 pub fn is_retryable(&self) -> bool {
812 self.category() == ErrorCategory::Transient
813 }
814
815 pub fn is_client_error(&self) -> bool {
821 matches!(
822 self.category(),
823 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
824 )
825 }
826
827 pub fn is_server_error(&self) -> bool {
833 matches!(
834 self.category(),
835 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
836 )
837 }
838}
839
840#[cfg(test)]
841mod tests {
842 use super::*;
843
844 #[test]
845 fn test_error_codes_plugin() {
846 assert_eq!(
847 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
848 100001
849 );
850 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
851 assert_eq!(
852 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
853 100003
854 );
855 assert_eq!(
856 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
857 100004
858 );
859 assert_eq!(
860 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
861 100005
862 );
863 assert_eq!(
864 BaseError::PluginCircularDependency("test".to_string()).code(),
865 100006
866 );
867 assert_eq!(
868 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
869 100007
870 );
871 assert_eq!(
872 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
873 100008
874 );
875 }
876
877 #[test]
878 fn test_error_codes_database() {
879 assert_eq!(
880 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
881 "reason".to_string()
882 ))
883 .code(),
884 200001
885 );
886 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
887 assert_eq!(
888 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
889 .code(),
890 200003
891 );
892 assert_eq!(
893 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
894 .code(),
895 200004
896 );
897 assert_eq!(
898 BaseError::DatabaseInitFailed("reason".to_string()).code(),
899 200005
900 );
901 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
902 assert_eq!(
903 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
904 "reason".to_string()
905 ))
906 .code(),
907 200009
908 );
909 }
910
911 #[cfg(feature = "http")]
912 #[test]
913 fn test_error_codes_http() {
914 assert_eq!(
916 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
917 300003
918 );
919 assert_eq!(BaseError::HttpTimeout.code(), 300004);
920 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
921 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
922 }
923
924 #[cfg(feature = "token")]
925 #[test]
926 fn test_error_codes_token() {
927 assert_eq!(
928 BaseError::TokenKeyInvalid("reason".to_string()).code(),
929 400001
930 );
931 assert_eq!(
932 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
933 jsonwebtoken::errors::ErrorKind::InvalidToken
934 ))
935 .code(),
936 400002
937 );
938 assert_eq!(
939 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
940 jsonwebtoken::errors::ErrorKind::InvalidToken
941 ))
942 .code(),
943 400003
944 );
945 assert_eq!(
946 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
947 jsonwebtoken::errors::ErrorKind::InvalidToken
948 ))
949 .code(),
950 400004
951 );
952 assert_eq!(BaseError::TokenExpired.code(), 400005);
953 assert_eq!(
954 BaseError::TokenTypeInvalid("reason".to_string()).code(),
955 400006
956 );
957 }
958
959 #[test]
960 fn test_error_codes_serialization() {
961 assert_eq!(
962 BaseError::JsonSerializeFailed("reason".to_string()).code(),
963 500001
964 );
965 assert_eq!(
966 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
967 500002
968 );
969 }
970
971 #[test]
972 fn test_error_codes_field_validation() {
973 assert_eq!(
974 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
975 600001
976 );
977 assert_eq!(
978 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
979 600002
980 );
981 assert_eq!(
982 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
983 600003
984 );
985 assert_eq!(
986 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
987 600004
988 );
989 assert_eq!(
990 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
991 600005
992 );
993 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
994 assert_eq!(
995 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
996 600007
997 );
998 assert_eq!(
999 BaseError::FieldPermissionDenied(
1000 "table".to_string(),
1001 "field".to_string(),
1002 "reason".to_string()
1003 )
1004 .code(),
1005 600008
1006 );
1007 }
1008
1009 #[test]
1010 fn test_error_codes_action_system() {
1011 assert_eq!(
1012 BaseError::ActionNotFound("test_action".to_string()).code(),
1013 700001
1014 );
1015 assert_eq!(
1016 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1017 700002
1018 );
1019 assert_eq!(
1020 BaseError::Unauthorized("Token 无效".to_string()).code(),
1021 700003
1022 );
1023 assert_eq!(
1024 BaseError::ParamMissing("user_id".to_string()).code(),
1025 700004
1026 );
1027 assert_eq!(
1028 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1029 700005
1030 );
1031 assert_eq!(
1032 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1033 700006
1034 );
1035 assert_eq!(
1036 BaseError::UserNotFound("user_123".to_string()).code(),
1037 700007
1038 );
1039 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1040 assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1041 assert_eq!(
1042 BaseError::RateLimitExceeded {
1043 retry_after_seconds: 30
1044 }
1045 .code(),
1046 700011
1047 );
1048 }
1049
1050 #[test]
1051 fn test_error_codes_general() {
1052 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1053 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1054 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1055 }
1056
1057 #[test]
1058 fn test_all_error_codes_are_nonzero() {
1059 let errors: Vec<BaseError> = vec![
1061 BaseError::PluginNotFound("test".to_string()),
1062 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1063 BaseError::HttpTimeout,
1064 BaseError::TokenExpired,
1065 BaseError::JsonSerializeFailed("test".to_string()),
1066 BaseError::FieldRequired("test".to_string()),
1067 BaseError::ActionNotFound("test".to_string()),
1068 BaseError::PermissionDenied("test".to_string()),
1069 BaseError::Unauthorized("test".to_string()),
1070 BaseError::ParamMissing("test".to_string()),
1071 BaseError::RecordNotFound("test".to_string()),
1072 BaseError::UserNotFound("test".to_string()),
1073 BaseError::InvalidPassword,
1074 BaseError::TableDefinitionNotSet,
1075 BaseError::RateLimitExceeded {
1076 retry_after_seconds: 30,
1077 },
1078 BaseError::Unknown("test".to_string()),
1079 ];
1080
1081 for error in errors {
1082 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1083 }
1084 }
1085
1086 #[test]
1088 fn test_database_error_source_chain() {
1089 use std::error::Error;
1090
1091 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1092 let base_err = BaseError::DatabaseQueryFailed(db_err);
1093
1094 let source = base_err.source();
1096 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1097 }
1098
1099 #[test]
1101 fn test_from_db_error_preserves_source() {
1102 use std::error::Error;
1103
1104 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1105 let base_err: BaseError = db_err.into();
1106
1107 assert!(base_err.source().is_some());
1109 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1110 }
1111
1112 #[test]
1113 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1114 use std::error::Error;
1115
1116 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1117 "connection refused".into(),
1118 ));
1119 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1120 "WRONGTYPE".into(),
1121 ));
1122
1123 assert_eq!(connection.code(), 210001);
1124 assert_eq!(operation.code(), 210004);
1125 assert!(connection.source().is_some());
1126 assert!(operation.source().is_some());
1127 }
1128
1129 #[test]
1130 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1131 use std::error::Error;
1132
1133 let error = BaseError::PluginLifecycleFailed {
1134 plugin: "audit".into(),
1135 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1136 source: Box::new(std::io::Error::other("flush failed")),
1137 };
1138
1139 assert_eq!(error.code(), 100008);
1140 assert_eq!(error.code_str(), "100008");
1141 assert!(error.to_string().contains("audit"));
1142 assert!(error.to_string().contains("shutdown"));
1143 assert!(error.source().is_some());
1144 }
1145
1146 #[test]
1148 fn test_code_str_matches_code() {
1149 let samples: Vec<BaseError> = vec![
1151 BaseError::PluginNotFound("p".into()),
1152 BaseError::PluginLifecycleFailed {
1153 plugin: "p".into(),
1154 stage: crate::plugin::PluginLifecycleStage::Initialize,
1155 source: Box::new(std::io::Error::other("init")),
1156 },
1157 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1158 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1159 BaseError::DatabaseNotInitialized,
1160 BaseError::RedisNotInitialized,
1161 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1162 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1163 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1164 BaseError::HttpTimeout,
1165 BaseError::TokenExpired,
1166 BaseError::TokenRevoked,
1167 BaseError::TokenRevocationStateInvalid("invalid".into()),
1168 BaseError::AuthorizationStale,
1169 BaseError::AuthorizationVersionInvalid,
1170 BaseError::AuthorizationCheckUnavailable,
1171 BaseError::JsonSerializeFailed("s".into()),
1172 BaseError::FieldNotFound("t".into(), "f".into()),
1173 BaseError::ParamInvalid("k".into(), "r".into()),
1174 BaseError::TableDefinitionNotSet,
1175 BaseError::RateLimitExceeded {
1176 retry_after_seconds: 30,
1177 },
1178 BaseError::ConfigError("c".into()),
1179 BaseError::Unknown("u".into()),
1180 ];
1181 for err in samples {
1182 let code = err.code();
1183 let code_str = err.code_str();
1184 assert_eq!(
1185 code_str.parse::<i32>().unwrap(),
1186 code,
1187 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1188 code_str,
1189 code,
1190 err
1191 );
1192 }
1193 }
1194
1195 #[test]
1197 fn test_error_category_coverage() {
1198 assert_eq!(
1200 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1201 ErrorCategory::Client
1202 );
1203 assert_eq!(
1204 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1205 ErrorCategory::Client
1206 );
1207 assert_eq!(
1209 BaseError::Unauthorized("u".into()).category(),
1210 ErrorCategory::Auth
1211 );
1212 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1213 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1214 assert_eq!(
1216 BaseError::RecordNotFound("r".into()).category(),
1217 ErrorCategory::NotFound
1218 );
1219 assert_eq!(
1220 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1221 ErrorCategory::NotFound
1222 );
1223 assert_eq!(
1225 BaseError::PluginAlreadyRegistered("p".into()).category(),
1226 ErrorCategory::Conflict
1227 );
1228 assert_eq!(
1230 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1231 .category(),
1232 ErrorCategory::Transient
1233 );
1234 assert_eq!(
1235 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1236 .category(),
1237 ErrorCategory::Transient
1238 );
1239 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1240 assert_eq!(
1242 BaseError::Unknown("u".into()).category(),
1243 ErrorCategory::Server
1244 );
1245 assert_eq!(
1246 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1247 ErrorCategory::Server
1248 );
1249 }
1250
1251 #[test]
1253 fn test_is_retryable() {
1254 assert!(
1255 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1256 .is_retryable()
1257 );
1258 assert!(BaseError::HttpTimeout.is_retryable());
1259 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1260 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1261 assert!(!BaseError::Unknown("u".into()).is_retryable());
1262 }
1263
1264 #[test]
1266 fn test_is_client_error() {
1267 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1268 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1269 assert!(BaseError::TokenExpired.is_client_error());
1270 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1271 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1272 assert!(
1273 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1274 .is_client_error()
1275 );
1276 assert!(!BaseError::Unknown("u".into()).is_client_error());
1277 }
1278
1279 #[test]
1281 fn test_is_server_error() {
1282 assert!(BaseError::Unknown("u".into()).is_server_error());
1283 assert!(
1284 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1285 .is_server_error()
1286 );
1287 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1288 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1289 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1290 }
1291}