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 响应体超过上限: 上限 {limit} 字节, 实际 {actual:?} 字节")]
174 HttpResponseTooLarge {
175 limit: usize,
177 actual: Option<u64>,
179 },
180
181 #[error("HTTP 请求超时")]
183 HttpTimeout,
184
185 #[error("HTTP 客户端已初始化")]
187 HttpClientAlreadyInitialized,
188
189 #[error("HTTP 客户端未初始化")]
191 HttpClientNotInitialized,
192
193 #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
195 HttpCircuitBreakerOpen(String),
196
197 #[error("Token 密钥无效: {0}")]
200 TokenKeyInvalid(String),
201
202 #[cfg(feature = "token")]
204 #[error("Token 生成失败: {0}")]
205 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
206
207 #[cfg(not(feature = "token"))]
209 #[error("Token 生成失败: {0}")]
210 TokenGenerateFailed(String),
211
212 #[cfg(feature = "token")]
214 #[error("Token 验证失败: {0}")]
215 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
216
217 #[cfg(not(feature = "token"))]
219 #[error("Token 验证失败: {0}")]
220 TokenVerifyFailed(String),
221
222 #[cfg(feature = "token")]
224 #[error("Token 解析失败: {0}")]
225 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
226
227 #[cfg(not(feature = "token"))]
229 #[error("Token 解析失败: {0}")]
230 TokenParseFailed(String),
231
232 #[error("Token 已过期")]
234 TokenExpired,
235
236 #[error("Token 已被撤销")]
238 TokenRevoked,
239
240 #[error("Token 撤销状态无效: {0}")]
242 TokenRevocationStateInvalid(String),
243
244 #[error("授权状态已变更,请刷新登录")]
246 AuthorizationStale,
247
248 #[error("授权版本无效")]
250 AuthorizationVersionInvalid,
251
252 #[error("授权状态暂时无法校验")]
254 AuthorizationCheckUnavailable,
255
256 #[error("Token 类型无效: {0}")]
258 TokenTypeInvalid(String),
259
260 #[error("JSON 序列化失败: {0}")]
263 JsonSerializeFailed(String),
264
265 #[error("JSON 反序列化失败: {0}")]
267 JsonDeserializeFailed(String),
268
269 #[error("字段类型无效 [{0}]: {1}")]
272 InvalidFieldType(String, String),
273
274 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
276 InvalidEnumValue(String, String),
277
278 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
280 StringTooLong(String, usize, usize),
281
282 #[error("JSON 格式无效 [{0}]: {1}")]
284 InvalidJsonFormat(String, String),
285
286 #[error("验证失败 [{0}]: {1}")]
288 ValidationFailed(String, String),
289
290 #[error("字段必填: {0}")]
292 FieldRequired(String),
293
294 #[error("字段未找到 [表: {0}]: {1}")]
296 FieldNotFound(String, String),
297
298 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
300 FieldPermissionDenied(String, String, String),
301
302 #[error("Action 未找到: {0}")]
305 ActionNotFound(String),
306
307 #[error("权限被拒绝: {0}")]
309 PermissionDenied(String),
310
311 #[error("未授权: {0}")]
313 Unauthorized(String),
314
315 #[error("参数缺失: {0}")]
317 ParamMissing(String),
318
319 #[error("参数无效 [{0}]: {1}")]
321 ParamInvalid(String, String),
322
323 #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
325 RateLimitExceeded {
326 retry_after_seconds: u64,
328 },
329
330 #[error("需要输入双重验证码")]
335 SecondFactorRequired,
336
337 #[error("记录未找到: {0}")]
339 RecordNotFound(String),
340
341 #[error("用户未找到: {0}")]
343 UserNotFound(String),
344
345 #[error("密码无效")]
347 InvalidPassword,
348
349 #[error("表定义未设置")]
351 TableDefinitionNotSet,
352
353 #[cfg(feature = "token")]
355 #[error("敏感操作需要重新认证")]
356 StepUpRequired(crate::action::StepUpChallenge),
357
358 #[error("配置错误: {0}")]
361 ConfigError(String),
362
363 #[error("IO 错误: {0}")]
365 IoError(String),
366
367 #[error("未知错误: {0}")]
369 Unknown(String),
370}
371
372#[allow(unreachable_patterns)]
384impl From<yang_db::DbError> for BaseError {
385 fn from(err: yang_db::DbError) -> Self {
386 use yang_db::DbError as D;
387 match &err {
388 D::QueryError(_)
390 | D::TableNotFound(_)
391 | D::TypeConversionError(_)
392 | D::DeserializationError(_)
393 | D::UnsupportedOperator(_)
394 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
395
396 D::ConstraintError(_)
398 | D::SqlSyntaxError(_)
399 | D::MissingWhereClause
400 | D::MissingGroupByClause
401 | D::InvalidArgument(_)
402 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
403
404 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
406
407 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
409
410 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
412
413 D::RedisCommandError(_)
415 | D::RedisPoolError(_)
416 | D::RedisTypeConversionError(_)
417 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
418
419 _ => BaseError::DatabaseQueryFailed(err),
421 }
422 }
423}
424
425impl From<std::io::Error> for BaseError {
427 fn from(err: std::io::Error) -> Self {
428 BaseError::IoError(err.to_string())
429 }
430}
431
432impl From<serde_json::Error> for BaseError {
434 fn from(err: serde_json::Error) -> Self {
435 if err.is_syntax() || err.is_data() || err.is_eof() {
436 BaseError::JsonDeserializeFailed(err.to_string())
437 } else {
438 BaseError::JsonSerializeFailed(err.to_string())
439 }
440 }
441}
442
443#[cfg(feature = "http")]
445impl From<reqwest::Error> for BaseError {
446 fn from(err: reqwest::Error) -> Self {
447 if err.is_timeout() {
448 BaseError::HttpTimeout
449 } else {
450 BaseError::HttpRequestFailed(err)
454 }
455 }
456}
457
458#[cfg(feature = "token")]
465impl From<jsonwebtoken::errors::Error> for BaseError {
466 fn from(err: jsonwebtoken::errors::Error) -> Self {
467 use jsonwebtoken::errors::ErrorKind;
468 match err.kind() {
469 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
470 ErrorKind::InvalidToken
471 | ErrorKind::InvalidSignature
472 | ErrorKind::InvalidIssuer
473 | ErrorKind::InvalidAudience
474 | ErrorKind::InvalidSubject
475 | ErrorKind::InvalidAlgorithm
476 | ErrorKind::MissingAlgorithm
477 | ErrorKind::ImmatureSignature
478 | ErrorKind::MissingRequiredClaim(_)
479 | ErrorKind::InvalidEcdsaKey
480 | ErrorKind::InvalidRsaKey(_)
481 | ErrorKind::InvalidKeyFormat
482 | ErrorKind::RsaFailedSigning
483 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
484 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
486 BaseError::TokenParseFailed(err)
487 }
488 _ => BaseError::TokenVerifyFailed(err),
490 }
491 }
492}
493
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
502#[non_exhaustive]
503pub enum ErrorCategory {
504 Client,
506 Auth,
508 NotFound,
510 Conflict,
512 Transient,
517 Server,
519}
520
521pub const NOT_READY_CODE: i32 = 900001;
526
527impl BaseError {
528 pub fn code(&self) -> i32 {
557 match self {
558 BaseError::PluginAlreadyRegistered(_) => 100001,
560 BaseError::PluginNotFound(_) => 100002,
561 BaseError::PluginRegisterFailed(_, _) => 100003,
562 BaseError::PluginInitFailed(_, _) => 100004,
563 BaseError::PluginDependencyMissing(_, _) => 100005,
564 BaseError::PluginCircularDependency(_) => 100006,
565 BaseError::PluginConfigInvalid(_, _) => 100007,
566 BaseError::PluginShutdownFailed(_, _) => 100008,
567 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
568 crate::plugin::PluginLifecycleStage::Register => 100003,
569 crate::plugin::PluginLifecycleStage::Initialize => 100004,
570 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
571 },
572
573 BaseError::DatabaseConnectionFailed(_) => 200001,
575 BaseError::DatabaseConnectionDbError(_) => 200011,
576 BaseError::DatabaseAlreadyInitialized => 200002,
577 BaseError::DatabaseQueryFailed(_) => 200003,
578 BaseError::DatabaseExecuteFailed(_) => 200004,
579 BaseError::DatabaseInitFailed(_) => 200005,
580 BaseError::DatabaseNotInitialized => 200008,
581 BaseError::DatabaseTransactionFailed(_) => 200009,
582 BaseError::MissingWhereClause(_) => 200010,
583
584 BaseError::RedisConnectionFailed(_) => 210001,
586 BaseError::RedisAlreadyInitialized => 210002,
587 BaseError::RedisNotInitialized => 210003,
588 BaseError::RedisOperationFailed(_) => 210004,
589 BaseError::RedisOperationDbError(_) => 210011,
590
591 BaseError::HttpClientCreateFailed(_) => 300001,
593 BaseError::HttpRequestFailed(_) => 300002,
594 BaseError::HttpResponseParseFailed(_) => 300003,
595 BaseError::HttpTimeout => 300004,
596 BaseError::HttpClientAlreadyInitialized => 300005,
597 BaseError::HttpClientNotInitialized => 300006,
598 BaseError::HttpCircuitBreakerOpen(_) => 300007,
599 BaseError::HttpResponseTooLarge { .. } => 300008,
600
601 BaseError::TokenKeyInvalid(_) => 400001,
603 BaseError::TokenGenerateFailed(_) => 400002,
604 BaseError::TokenVerifyFailed(_) => 400003,
605 BaseError::TokenParseFailed(_) => 400004,
606 BaseError::TokenExpired => 400005,
607 BaseError::TokenTypeInvalid(_) => 400006,
608 BaseError::TokenRevoked => 400007,
609 BaseError::TokenRevocationStateInvalid(_) => 400008,
610 BaseError::AuthorizationStale => 400009,
611 BaseError::AuthorizationVersionInvalid => 400010,
612 BaseError::AuthorizationCheckUnavailable => 400011,
613
614 BaseError::JsonSerializeFailed(_) => 500001,
616 BaseError::JsonDeserializeFailed(_) => 500002,
617
618 BaseError::InvalidFieldType(_, _) => 600001,
620 BaseError::InvalidEnumValue(_, _) => 600002,
621 BaseError::StringTooLong(_, _, _) => 600003,
622 BaseError::InvalidJsonFormat(_, _) => 600004,
623 BaseError::ValidationFailed(_, _) => 600005,
624 BaseError::FieldRequired(_) => 600006,
625 BaseError::FieldNotFound(_, _) => 600007,
626 BaseError::FieldPermissionDenied(_, _, _) => 600008,
627
628 BaseError::ActionNotFound(_) => 700001,
630 BaseError::PermissionDenied(_) => 700002,
631 BaseError::Unauthorized(_) => 700003,
632 BaseError::ParamMissing(_) => 700004,
633 BaseError::ParamInvalid(_, _) => 700005,
634 BaseError::RecordNotFound(_) => 700006,
635 BaseError::UserNotFound(_) => 700007,
636 BaseError::InvalidPassword => 700008,
637 BaseError::TableDefinitionNotSet => 700009,
638 #[cfg(feature = "token")]
639 BaseError::StepUpRequired(_) => 700010,
640 BaseError::RateLimitExceeded { .. } => 700011,
641 BaseError::SecondFactorRequired => 700012,
642
643 BaseError::ConfigError(_) => 900001,
645 BaseError::IoError(_) => 900002,
646 BaseError::Unknown(_) => 999999,
647 }
648 }
649
650 pub fn code_str(&self) -> &'static str {
657 match self {
658 BaseError::PluginAlreadyRegistered(_) => "100001",
660 BaseError::PluginNotFound(_) => "100002",
661 BaseError::PluginRegisterFailed(_, _) => "100003",
662 BaseError::PluginInitFailed(_, _) => "100004",
663 BaseError::PluginDependencyMissing(_, _) => "100005",
664 BaseError::PluginCircularDependency(_) => "100006",
665 BaseError::PluginConfigInvalid(_, _) => "100007",
666 BaseError::PluginShutdownFailed(_, _) => "100008",
667 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
668 crate::plugin::PluginLifecycleStage::Register => "100003",
669 crate::plugin::PluginLifecycleStage::Initialize => "100004",
670 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
671 },
672 BaseError::DatabaseConnectionFailed(_) => "200001",
674 BaseError::DatabaseConnectionDbError(_) => "200011",
675 BaseError::DatabaseAlreadyInitialized => "200002",
676 BaseError::DatabaseQueryFailed(_) => "200003",
677 BaseError::DatabaseExecuteFailed(_) => "200004",
678 BaseError::DatabaseInitFailed(_) => "200005",
679 BaseError::DatabaseNotInitialized => "200008",
680 BaseError::DatabaseTransactionFailed(_) => "200009",
681 BaseError::MissingWhereClause(_) => "200010",
682 BaseError::RedisConnectionFailed(_) => "210001",
684 BaseError::RedisAlreadyInitialized => "210002",
685 BaseError::RedisNotInitialized => "210003",
686 BaseError::RedisOperationFailed(_) => "210004",
687 BaseError::RedisOperationDbError(_) => "210011",
688 BaseError::HttpClientCreateFailed(_) => "300001",
690 BaseError::HttpRequestFailed(_) => "300002",
691 BaseError::HttpResponseParseFailed(_) => "300003",
692 BaseError::HttpTimeout => "300004",
693 BaseError::HttpClientAlreadyInitialized => "300005",
694 BaseError::HttpClientNotInitialized => "300006",
695 BaseError::HttpCircuitBreakerOpen(_) => "300007",
696 BaseError::HttpResponseTooLarge { .. } => "300008",
697 BaseError::TokenKeyInvalid(_) => "400001",
699 BaseError::TokenGenerateFailed(_) => "400002",
700 BaseError::TokenVerifyFailed(_) => "400003",
701 BaseError::TokenParseFailed(_) => "400004",
702 BaseError::TokenExpired => "400005",
703 BaseError::TokenTypeInvalid(_) => "400006",
704 BaseError::TokenRevoked => "400007",
705 BaseError::TokenRevocationStateInvalid(_) => "400008",
706 BaseError::AuthorizationStale => "400009",
707 BaseError::AuthorizationVersionInvalid => "400010",
708 BaseError::AuthorizationCheckUnavailable => "400011",
709 BaseError::JsonSerializeFailed(_) => "500001",
711 BaseError::JsonDeserializeFailed(_) => "500002",
712 BaseError::InvalidFieldType(_, _) => "600001",
714 BaseError::InvalidEnumValue(_, _) => "600002",
715 BaseError::StringTooLong(_, _, _) => "600003",
716 BaseError::InvalidJsonFormat(_, _) => "600004",
717 BaseError::ValidationFailed(_, _) => "600005",
718 BaseError::FieldRequired(_) => "600006",
719 BaseError::FieldNotFound(_, _) => "600007",
720 BaseError::FieldPermissionDenied(_, _, _) => "600008",
721 BaseError::ActionNotFound(_) => "700001",
723 BaseError::PermissionDenied(_) => "700002",
724 BaseError::Unauthorized(_) => "700003",
725 BaseError::ParamMissing(_) => "700004",
726 BaseError::ParamInvalid(_, _) => "700005",
727 BaseError::RecordNotFound(_) => "700006",
728 BaseError::UserNotFound(_) => "700007",
729 BaseError::InvalidPassword => "700008",
730 BaseError::TableDefinitionNotSet => "700009",
731 #[cfg(feature = "token")]
732 BaseError::StepUpRequired(_) => "700010",
733 BaseError::RateLimitExceeded { .. } => "700011",
734 BaseError::SecondFactorRequired => "700012",
735 BaseError::ConfigError(_) => "900001",
737 BaseError::IoError(_) => "900002",
738 BaseError::Unknown(_) => "999999",
739 }
740 }
741
742 pub fn category(&self) -> ErrorCategory {
752 use ErrorCategory as C;
753 match self {
754 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
756 BaseError::PluginCircularDependency(_) => C::Client,
757 BaseError::PluginDependencyMissing(_, _) => C::Client,
758 BaseError::PluginConfigInvalid(_, _) => C::Client,
759 BaseError::PluginNotFound(_)
760 | BaseError::PluginRegisterFailed(_, _)
761 | BaseError::PluginInitFailed(_, _)
762 | BaseError::PluginShutdownFailed(_, _)
763 | BaseError::PluginLifecycleFailed { .. } => C::Server,
764 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
767 C::Transient
768 }
769 BaseError::MissingWhereClause(_) => C::Client,
770 BaseError::DatabaseAlreadyInitialized
771 | BaseError::DatabaseNotInitialized
772 | BaseError::DatabaseInitFailed(_) => C::Server,
773 BaseError::DatabaseQueryFailed(_)
775 | BaseError::DatabaseExecuteFailed(_)
776 | BaseError::DatabaseTransactionFailed(_) => C::Server,
777 BaseError::RedisConnectionFailed(_) => C::Transient,
779 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
780 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
781 match source.category() {
782 yang_db::DbErrorCategory::Transient => C::Transient,
783 yang_db::DbErrorCategory::Conflict => C::Conflict,
784 yang_db::DbErrorCategory::Client => C::Client,
785 yang_db::DbErrorCategory::NotFound => C::NotFound,
786 yang_db::DbErrorCategory::Server => C::Server,
787 _ => C::Server,
788 }
789 }
790 BaseError::HttpClientCreateFailed(_)
792 | BaseError::HttpClientNotInitialized
793 | BaseError::HttpClientAlreadyInitialized => C::Client,
794 BaseError::HttpResponseParseFailed(_) => C::Client,
796 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
797 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
799 BaseError::HttpResponseTooLarge { .. } => C::Server,
801 BaseError::TokenKeyInvalid(_)
803 | BaseError::TokenGenerateFailed(_)
804 | BaseError::TokenTypeInvalid(_)
805 | BaseError::TokenParseFailed(_) => C::Client,
806 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
807 C::Auth
808 }
809 BaseError::TokenRevocationStateInvalid(_) => C::Server,
810 BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
811 BaseError::AuthorizationCheckUnavailable => C::Transient,
812 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
814 BaseError::InvalidFieldType(_, _)
816 | BaseError::InvalidEnumValue(_, _)
817 | BaseError::StringTooLong(_, _, _)
818 | BaseError::InvalidJsonFormat(_, _)
819 | BaseError::ValidationFailed(_, _)
820 | BaseError::FieldRequired(_)
821 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
822 BaseError::FieldNotFound(_, _) => C::NotFound,
823 BaseError::Unauthorized(_)
825 | BaseError::PermissionDenied(_)
826 | BaseError::SecondFactorRequired => C::Auth,
827 BaseError::ParamMissing(_)
828 | BaseError::ParamInvalid(_, _)
829 | BaseError::RateLimitExceeded { .. } => C::Client,
830 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
831 BaseError::InvalidPassword => C::Auth,
832 BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
833 #[cfg(feature = "token")]
834 BaseError::StepUpRequired(_) => C::Client,
835 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
837 }
838 }
839
840 pub fn is_retryable(&self) -> bool {
842 self.category() == ErrorCategory::Transient
843 }
844
845 pub fn is_client_error(&self) -> bool {
851 matches!(
852 self.category(),
853 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
854 )
855 }
856
857 pub fn is_server_error(&self) -> bool {
863 matches!(
864 self.category(),
865 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
866 )
867 }
868}
869
870#[cfg(test)]
871mod tests {
872 use super::*;
873
874 #[test]
875 fn test_not_ready_code_is_stable() {
876 assert_eq!(NOT_READY_CODE, 900001);
877 }
878
879 #[test]
880 fn test_error_codes_plugin() {
881 assert_eq!(
882 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
883 100001
884 );
885 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
886 assert_eq!(
887 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
888 100003
889 );
890 assert_eq!(
891 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
892 100004
893 );
894 assert_eq!(
895 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
896 100005
897 );
898 assert_eq!(
899 BaseError::PluginCircularDependency("test".to_string()).code(),
900 100006
901 );
902 assert_eq!(
903 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
904 100007
905 );
906 assert_eq!(
907 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
908 100008
909 );
910 }
911
912 #[test]
913 fn test_error_codes_database() {
914 assert_eq!(
915 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
916 "reason".to_string()
917 ))
918 .code(),
919 200001
920 );
921 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
922 assert_eq!(
923 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
924 .code(),
925 200003
926 );
927 assert_eq!(
928 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
929 .code(),
930 200004
931 );
932 assert_eq!(
933 BaseError::DatabaseInitFailed("reason".to_string()).code(),
934 200005
935 );
936 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
937 assert_eq!(
938 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
939 "reason".to_string()
940 ))
941 .code(),
942 200009
943 );
944 }
945
946 #[cfg(feature = "http")]
947 #[test]
948 fn test_error_codes_http() {
949 assert_eq!(
951 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
952 300003
953 );
954 assert_eq!(BaseError::HttpTimeout.code(), 300004);
955 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
956 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
957 }
958
959 #[cfg(feature = "token")]
960 #[test]
961 fn test_error_codes_token() {
962 assert_eq!(
963 BaseError::TokenKeyInvalid("reason".to_string()).code(),
964 400001
965 );
966 assert_eq!(
967 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
968 jsonwebtoken::errors::ErrorKind::InvalidToken
969 ))
970 .code(),
971 400002
972 );
973 assert_eq!(
974 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
975 jsonwebtoken::errors::ErrorKind::InvalidToken
976 ))
977 .code(),
978 400003
979 );
980 assert_eq!(
981 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
982 jsonwebtoken::errors::ErrorKind::InvalidToken
983 ))
984 .code(),
985 400004
986 );
987 assert_eq!(BaseError::TokenExpired.code(), 400005);
988 assert_eq!(
989 BaseError::TokenTypeInvalid("reason".to_string()).code(),
990 400006
991 );
992 }
993
994 #[test]
995 fn test_error_codes_serialization() {
996 assert_eq!(
997 BaseError::JsonSerializeFailed("reason".to_string()).code(),
998 500001
999 );
1000 assert_eq!(
1001 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
1002 500002
1003 );
1004 }
1005
1006 #[test]
1007 fn test_error_codes_field_validation() {
1008 assert_eq!(
1009 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
1010 600001
1011 );
1012 assert_eq!(
1013 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1014 600002
1015 );
1016 assert_eq!(
1017 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1018 600003
1019 );
1020 assert_eq!(
1021 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1022 600004
1023 );
1024 assert_eq!(
1025 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1026 600005
1027 );
1028 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1029 assert_eq!(
1030 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1031 600007
1032 );
1033 assert_eq!(
1034 BaseError::FieldPermissionDenied(
1035 "table".to_string(),
1036 "field".to_string(),
1037 "reason".to_string()
1038 )
1039 .code(),
1040 600008
1041 );
1042 }
1043
1044 #[test]
1045 fn test_error_codes_action_system() {
1046 assert_eq!(
1047 BaseError::ActionNotFound("test_action".to_string()).code(),
1048 700001
1049 );
1050 assert_eq!(
1051 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1052 700002
1053 );
1054 assert_eq!(
1055 BaseError::Unauthorized("Token 无效".to_string()).code(),
1056 700003
1057 );
1058 assert_eq!(
1059 BaseError::ParamMissing("user_id".to_string()).code(),
1060 700004
1061 );
1062 assert_eq!(
1063 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1064 700005
1065 );
1066 assert_eq!(
1067 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1068 700006
1069 );
1070 assert_eq!(
1071 BaseError::UserNotFound("user_123".to_string()).code(),
1072 700007
1073 );
1074 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1075 assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1076 assert_eq!(
1077 BaseError::RateLimitExceeded {
1078 retry_after_seconds: 30
1079 }
1080 .code(),
1081 700011
1082 );
1083 assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
1084 assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
1085 }
1086
1087 #[test]
1088 fn test_error_codes_general() {
1089 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1090 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1091 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1092 }
1093
1094 #[test]
1095 fn test_all_error_codes_are_nonzero() {
1096 let errors: Vec<BaseError> = vec![
1098 BaseError::PluginNotFound("test".to_string()),
1099 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1100 BaseError::HttpTimeout,
1101 BaseError::TokenExpired,
1102 BaseError::JsonSerializeFailed("test".to_string()),
1103 BaseError::FieldRequired("test".to_string()),
1104 BaseError::ActionNotFound("test".to_string()),
1105 BaseError::PermissionDenied("test".to_string()),
1106 BaseError::Unauthorized("test".to_string()),
1107 BaseError::ParamMissing("test".to_string()),
1108 BaseError::RecordNotFound("test".to_string()),
1109 BaseError::UserNotFound("test".to_string()),
1110 BaseError::InvalidPassword,
1111 BaseError::TableDefinitionNotSet,
1112 BaseError::RateLimitExceeded {
1113 retry_after_seconds: 30,
1114 },
1115 BaseError::Unknown("test".to_string()),
1116 ];
1117
1118 for error in errors {
1119 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1120 }
1121 }
1122
1123 #[test]
1125 fn test_database_error_source_chain() {
1126 use std::error::Error;
1127
1128 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1129 let base_err = BaseError::DatabaseQueryFailed(db_err);
1130
1131 let source = base_err.source();
1133 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1134 }
1135
1136 #[test]
1138 fn test_from_db_error_preserves_source() {
1139 use std::error::Error;
1140
1141 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1142 let base_err: BaseError = db_err.into();
1143
1144 assert!(base_err.source().is_some());
1146 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1147 }
1148
1149 #[test]
1150 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1151 use std::error::Error;
1152
1153 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1154 "connection refused".into(),
1155 ));
1156 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1157 "WRONGTYPE".into(),
1158 ));
1159
1160 assert_eq!(connection.code(), 210001);
1161 assert_eq!(operation.code(), 210004);
1162 assert!(connection.source().is_some());
1163 assert!(operation.source().is_some());
1164 }
1165
1166 #[test]
1167 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1168 use std::error::Error;
1169
1170 let error = BaseError::PluginLifecycleFailed {
1171 plugin: "audit".into(),
1172 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1173 source: Box::new(std::io::Error::other("flush failed")),
1174 };
1175
1176 assert_eq!(error.code(), 100008);
1177 assert_eq!(error.code_str(), "100008");
1178 assert!(error.to_string().contains("audit"));
1179 assert!(error.to_string().contains("shutdown"));
1180 assert!(error.source().is_some());
1181 }
1182
1183 #[test]
1185 fn test_code_str_matches_code() {
1186 let samples: Vec<BaseError> = vec![
1188 BaseError::PluginNotFound("p".into()),
1189 BaseError::PluginLifecycleFailed {
1190 plugin: "p".into(),
1191 stage: crate::plugin::PluginLifecycleStage::Initialize,
1192 source: Box::new(std::io::Error::other("init")),
1193 },
1194 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1195 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1196 BaseError::DatabaseNotInitialized,
1197 BaseError::RedisNotInitialized,
1198 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1199 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1200 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1201 BaseError::HttpTimeout,
1202 BaseError::TokenExpired,
1203 BaseError::TokenRevoked,
1204 BaseError::TokenRevocationStateInvalid("invalid".into()),
1205 BaseError::AuthorizationStale,
1206 BaseError::AuthorizationVersionInvalid,
1207 BaseError::AuthorizationCheckUnavailable,
1208 BaseError::JsonSerializeFailed("s".into()),
1209 BaseError::FieldNotFound("t".into(), "f".into()),
1210 BaseError::ParamInvalid("k".into(), "r".into()),
1211 BaseError::TableDefinitionNotSet,
1212 BaseError::RateLimitExceeded {
1213 retry_after_seconds: 30,
1214 },
1215 BaseError::SecondFactorRequired,
1216 BaseError::ConfigError("c".into()),
1217 BaseError::Unknown("u".into()),
1218 ];
1219 for err in samples {
1220 let code = err.code();
1221 let code_str = err.code_str();
1222 assert_eq!(
1223 code_str.parse::<i32>().unwrap(),
1224 code,
1225 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1226 code_str,
1227 code,
1228 err
1229 );
1230 }
1231 }
1232
1233 #[test]
1235 fn test_error_category_coverage() {
1236 assert_eq!(
1238 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1239 ErrorCategory::Client
1240 );
1241 assert_eq!(
1242 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1243 ErrorCategory::Client
1244 );
1245 assert_eq!(
1247 BaseError::Unauthorized("u".into()).category(),
1248 ErrorCategory::Auth
1249 );
1250 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1251 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1252 assert_eq!(
1253 BaseError::SecondFactorRequired.category(),
1254 ErrorCategory::Auth
1255 );
1256 assert_eq!(
1258 BaseError::RecordNotFound("r".into()).category(),
1259 ErrorCategory::NotFound
1260 );
1261 assert_eq!(
1262 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1263 ErrorCategory::NotFound
1264 );
1265 assert_eq!(
1267 BaseError::PluginAlreadyRegistered("p".into()).category(),
1268 ErrorCategory::Conflict
1269 );
1270 assert_eq!(
1272 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1273 .category(),
1274 ErrorCategory::Transient
1275 );
1276 assert_eq!(
1277 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1278 .category(),
1279 ErrorCategory::Transient
1280 );
1281 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1282 assert_eq!(
1284 BaseError::Unknown("u".into()).category(),
1285 ErrorCategory::Server
1286 );
1287 assert_eq!(
1288 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1289 ErrorCategory::Server
1290 );
1291 }
1292
1293 #[test]
1295 fn test_is_retryable() {
1296 assert!(
1297 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1298 .is_retryable()
1299 );
1300 assert!(BaseError::HttpTimeout.is_retryable());
1301 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1302 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1303 assert!(!BaseError::Unknown("u".into()).is_retryable());
1304 }
1305
1306 #[test]
1308 fn test_is_client_error() {
1309 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1310 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1311 assert!(BaseError::TokenExpired.is_client_error());
1312 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1313 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1314 assert!(
1315 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1316 .is_client_error()
1317 );
1318 assert!(!BaseError::Unknown("u".into()).is_client_error());
1319 }
1320
1321 #[test]
1323 fn test_is_server_error() {
1324 assert!(BaseError::Unknown("u".into()).is_server_error());
1325 assert!(
1326 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1327 .is_server_error()
1328 );
1329 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1330 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1331 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1332 }
1333}