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("上游服务暂不可用: {0}")]
208 UpstreamUnavailable(String),
209
210 #[error("Token 密钥无效: {0}")]
213 TokenKeyInvalid(String),
214
215 #[cfg(feature = "token")]
217 #[error("Token 生成失败: {0}")]
218 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
219
220 #[cfg(not(feature = "token"))]
222 #[error("Token 生成失败: {0}")]
223 TokenGenerateFailed(String),
224
225 #[cfg(feature = "token")]
227 #[error("Token 验证失败: {0}")]
228 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
229
230 #[cfg(not(feature = "token"))]
232 #[error("Token 验证失败: {0}")]
233 TokenVerifyFailed(String),
234
235 #[cfg(feature = "token")]
237 #[error("Token 解析失败: {0}")]
238 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
239
240 #[cfg(not(feature = "token"))]
242 #[error("Token 解析失败: {0}")]
243 TokenParseFailed(String),
244
245 #[error("Token 已过期")]
247 TokenExpired,
248
249 #[error("Token 已被撤销")]
251 TokenRevoked,
252
253 #[error("Token 撤销状态无效: {0}")]
255 TokenRevocationStateInvalid(String),
256
257 #[error("授权状态已变更,请刷新登录")]
259 AuthorizationStale,
260
261 #[error("授权版本无效")]
263 AuthorizationVersionInvalid,
264
265 #[error("授权状态暂时无法校验")]
267 AuthorizationCheckUnavailable,
268
269 #[error("Token 类型无效: {0}")]
271 TokenTypeInvalid(String),
272
273 #[error("JSON 序列化失败: {0}")]
276 JsonSerializeFailed(String),
277
278 #[error("JSON 反序列化失败: {0}")]
280 JsonDeserializeFailed(String),
281
282 #[error("字段类型无效 [{0}]: {1}")]
285 InvalidFieldType(String, String),
286
287 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
289 InvalidEnumValue(String, String),
290
291 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
293 StringTooLong(String, usize, usize),
294
295 #[error("JSON 格式无效 [{0}]: {1}")]
297 InvalidJsonFormat(String, String),
298
299 #[error("验证失败 [{0}]: {1}")]
301 ValidationFailed(String, String),
302
303 #[error("字段必填: {0}")]
305 FieldRequired(String),
306
307 #[error("字段未找到 [表: {0}]: {1}")]
309 FieldNotFound(String, String),
310
311 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
313 FieldPermissionDenied(String, String, String),
314
315 #[error("Action 未找到: {0}")]
318 ActionNotFound(String),
319
320 #[error("权限被拒绝: {0}")]
322 PermissionDenied(String),
323
324 #[error("未授权: {0}")]
326 Unauthorized(String),
327
328 #[error("参数缺失: {0}")]
330 ParamMissing(String),
331
332 #[error("参数无效 [{0}]: {1}")]
334 ParamInvalid(String, String),
335
336 #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
338 RateLimitExceeded {
339 retry_after_seconds: u64,
341 },
342
343 #[error("需要输入双重验证码")]
348 SecondFactorRequired,
349
350 #[error("记录未找到: {0}")]
352 RecordNotFound(String),
353
354 #[error("用户未找到: {0}")]
356 UserNotFound(String),
357
358 #[error("密码无效")]
360 InvalidPassword,
361
362 #[error("表定义未设置")]
364 TableDefinitionNotSet,
365
366 #[cfg(feature = "token")]
368 #[error("敏感操作需要重新认证")]
369 StepUpRequired(crate::action::StepUpChallenge),
370
371 #[error("配置错误: {0}")]
374 ConfigError(String),
375
376 #[error("IO 错误: {0}")]
378 IoError(String),
379
380 #[error("未知错误: {0}")]
382 Unknown(String),
383}
384
385fn duplicate_key_field(message: &str) -> Option<String> {
401 if message.contains("Duplicate entry") {
402 if let Some((_, rest)) = message.split_once("for key '") {
403 let raw = rest.split('\'').next().unwrap_or_default();
405 let last = raw.rsplit('.').next().unwrap_or(raw);
406 if !last.is_empty() {
407 return Some(last.to_string());
408 }
409 }
410 }
411 if message.contains("duplicate key value violates unique constraint") {
412 if let Some((_, rest)) = message.split_once("unique constraint \"") {
413 let name = rest.split('"').next().unwrap_or_default();
414 if !name.is_empty() {
415 return Some(name.to_string());
416 }
417 }
418 }
419 None
420}
421
422#[allow(unreachable_patterns)]
437impl From<yang_db::DbError> for BaseError {
438 fn from(err: yang_db::DbError) -> Self {
439 use yang_db::DbError as D;
440 match &err {
441 D::QueryError(_)
443 | D::TableNotFound(_)
444 | D::TypeConversionError(_)
445 | D::DeserializationError(_)
446 | D::UnsupportedOperator(_)
447 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
448
449 D::ConstraintError(message) => match duplicate_key_field(message) {
452 Some(field) => BaseError::ParamInvalid(field, "该值已存在".to_string()),
453 None => BaseError::DatabaseExecuteFailed(err),
454 },
455
456 D::SqlSyntaxError(_)
458 | D::MissingWhereClause
459 | D::MissingGroupByClause
460 | D::InvalidArgument(_)
461 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
462
463 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
465
466 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
468
469 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
471
472 D::RedisCommandError(_)
474 | D::RedisPoolError(_)
475 | D::RedisTypeConversionError(_)
476 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
477
478 _ => BaseError::DatabaseQueryFailed(err),
480 }
481 }
482}
483
484impl From<std::io::Error> for BaseError {
486 fn from(err: std::io::Error) -> Self {
487 BaseError::IoError(err.to_string())
488 }
489}
490
491impl From<serde_json::Error> for BaseError {
493 fn from(err: serde_json::Error) -> Self {
494 if err.is_syntax() || err.is_data() || err.is_eof() {
495 BaseError::JsonDeserializeFailed(err.to_string())
496 } else {
497 BaseError::JsonSerializeFailed(err.to_string())
498 }
499 }
500}
501
502#[cfg(feature = "http")]
504impl From<reqwest::Error> for BaseError {
505 fn from(err: reqwest::Error) -> Self {
506 if err.is_timeout() {
507 BaseError::HttpTimeout
508 } else {
509 BaseError::HttpRequestFailed(err)
513 }
514 }
515}
516
517#[cfg(feature = "token")]
524impl From<jsonwebtoken::errors::Error> for BaseError {
525 fn from(err: jsonwebtoken::errors::Error) -> Self {
526 use jsonwebtoken::errors::ErrorKind;
527 match err.kind() {
528 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
529 ErrorKind::InvalidToken
530 | ErrorKind::InvalidSignature
531 | ErrorKind::InvalidIssuer
532 | ErrorKind::InvalidAudience
533 | ErrorKind::InvalidSubject
534 | ErrorKind::InvalidAlgorithm
535 | ErrorKind::MissingAlgorithm
536 | ErrorKind::ImmatureSignature
537 | ErrorKind::MissingRequiredClaim(_)
538 | ErrorKind::InvalidEcdsaKey
539 | ErrorKind::InvalidRsaKey(_)
540 | ErrorKind::InvalidKeyFormat
541 | ErrorKind::RsaFailedSigning
542 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
543 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
545 BaseError::TokenParseFailed(err)
546 }
547 _ => BaseError::TokenVerifyFailed(err),
549 }
550 }
551}
552
553#[derive(Debug, Clone, Copy, PartialEq, Eq)]
561#[non_exhaustive]
562pub enum ErrorCategory {
563 Client,
565 Auth,
567 NotFound,
569 Conflict,
571 Transient,
576 Server,
578}
579
580pub const NOT_READY_CODE: i32 = 900001;
585
586impl BaseError {
587 pub fn code(&self) -> i32 {
616 match self {
617 BaseError::PluginAlreadyRegistered(_) => 100001,
619 BaseError::PluginNotFound(_) => 100002,
620 BaseError::PluginRegisterFailed(_, _) => 100003,
621 BaseError::PluginInitFailed(_, _) => 100004,
622 BaseError::PluginDependencyMissing(_, _) => 100005,
623 BaseError::PluginCircularDependency(_) => 100006,
624 BaseError::PluginConfigInvalid(_, _) => 100007,
625 BaseError::PluginShutdownFailed(_, _) => 100008,
626 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
627 crate::plugin::PluginLifecycleStage::Register => 100003,
628 crate::plugin::PluginLifecycleStage::Initialize => 100004,
629 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
630 },
631
632 BaseError::DatabaseConnectionFailed(_) => 200001,
634 BaseError::DatabaseConnectionDbError(_) => 200011,
635 BaseError::DatabaseAlreadyInitialized => 200002,
636 BaseError::DatabaseQueryFailed(_) => 200003,
637 BaseError::DatabaseExecuteFailed(_) => 200004,
638 BaseError::DatabaseInitFailed(_) => 200005,
639 BaseError::DatabaseNotInitialized => 200008,
640 BaseError::DatabaseTransactionFailed(_) => 200009,
641 BaseError::MissingWhereClause(_) => 200010,
642
643 BaseError::RedisConnectionFailed(_) => 210001,
645 BaseError::RedisAlreadyInitialized => 210002,
646 BaseError::RedisNotInitialized => 210003,
647 BaseError::RedisOperationFailed(_) => 210004,
648 BaseError::RedisOperationDbError(_) => 210011,
649
650 BaseError::HttpClientCreateFailed(_) => 300001,
652 BaseError::HttpRequestFailed(_) => 300002,
653 BaseError::HttpResponseParseFailed(_) => 300003,
654 BaseError::HttpTimeout => 300004,
655 BaseError::HttpClientAlreadyInitialized => 300005,
656 BaseError::HttpClientNotInitialized => 300006,
657 BaseError::HttpCircuitBreakerOpen(_) => 300007,
658 BaseError::HttpResponseTooLarge { .. } => 300008,
659 BaseError::UpstreamUnavailable(_) => 300009,
662
663 BaseError::TokenKeyInvalid(_) => 400001,
665 BaseError::TokenGenerateFailed(_) => 400002,
666 BaseError::TokenVerifyFailed(_) => 400003,
667 BaseError::TokenParseFailed(_) => 400004,
668 BaseError::TokenExpired => 400005,
669 BaseError::TokenTypeInvalid(_) => 400006,
670 BaseError::TokenRevoked => 400007,
671 BaseError::TokenRevocationStateInvalid(_) => 400008,
672 BaseError::AuthorizationStale => 400009,
673 BaseError::AuthorizationVersionInvalid => 400010,
674 BaseError::AuthorizationCheckUnavailable => 400011,
675
676 BaseError::JsonSerializeFailed(_) => 500001,
678 BaseError::JsonDeserializeFailed(_) => 500002,
679
680 BaseError::InvalidFieldType(_, _) => 600001,
682 BaseError::InvalidEnumValue(_, _) => 600002,
683 BaseError::StringTooLong(_, _, _) => 600003,
684 BaseError::InvalidJsonFormat(_, _) => 600004,
685 BaseError::ValidationFailed(_, _) => 600005,
686 BaseError::FieldRequired(_) => 600006,
687 BaseError::FieldNotFound(_, _) => 600007,
688 BaseError::FieldPermissionDenied(_, _, _) => 600008,
689
690 BaseError::ActionNotFound(_) => 700001,
692 BaseError::PermissionDenied(_) => 700002,
693 BaseError::Unauthorized(_) => 700003,
694 BaseError::ParamMissing(_) => 700004,
695 BaseError::ParamInvalid(_, _) => 700005,
696 BaseError::RecordNotFound(_) => 700006,
697 BaseError::UserNotFound(_) => 700007,
698 BaseError::InvalidPassword => 700008,
699 BaseError::TableDefinitionNotSet => 700009,
700 #[cfg(feature = "token")]
701 BaseError::StepUpRequired(_) => 700010,
702 BaseError::RateLimitExceeded { .. } => 700011,
703 BaseError::SecondFactorRequired => 700012,
704
705 BaseError::ConfigError(_) => 900001,
707 BaseError::IoError(_) => 900002,
708 BaseError::Unknown(_) => 999999,
709 }
710 }
711
712 pub fn code_str(&self) -> &'static str {
719 match self {
720 BaseError::PluginAlreadyRegistered(_) => "100001",
722 BaseError::PluginNotFound(_) => "100002",
723 BaseError::PluginRegisterFailed(_, _) => "100003",
724 BaseError::PluginInitFailed(_, _) => "100004",
725 BaseError::PluginDependencyMissing(_, _) => "100005",
726 BaseError::PluginCircularDependency(_) => "100006",
727 BaseError::PluginConfigInvalid(_, _) => "100007",
728 BaseError::PluginShutdownFailed(_, _) => "100008",
729 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
730 crate::plugin::PluginLifecycleStage::Register => "100003",
731 crate::plugin::PluginLifecycleStage::Initialize => "100004",
732 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
733 },
734 BaseError::DatabaseConnectionFailed(_) => "200001",
736 BaseError::DatabaseConnectionDbError(_) => "200011",
737 BaseError::DatabaseAlreadyInitialized => "200002",
738 BaseError::DatabaseQueryFailed(_) => "200003",
739 BaseError::DatabaseExecuteFailed(_) => "200004",
740 BaseError::DatabaseInitFailed(_) => "200005",
741 BaseError::DatabaseNotInitialized => "200008",
742 BaseError::DatabaseTransactionFailed(_) => "200009",
743 BaseError::MissingWhereClause(_) => "200010",
744 BaseError::RedisConnectionFailed(_) => "210001",
746 BaseError::RedisAlreadyInitialized => "210002",
747 BaseError::RedisNotInitialized => "210003",
748 BaseError::RedisOperationFailed(_) => "210004",
749 BaseError::RedisOperationDbError(_) => "210011",
750 BaseError::HttpClientCreateFailed(_) => "300001",
752 BaseError::HttpRequestFailed(_) => "300002",
753 BaseError::HttpResponseParseFailed(_) => "300003",
754 BaseError::HttpTimeout => "300004",
755 BaseError::HttpClientAlreadyInitialized => "300005",
756 BaseError::HttpClientNotInitialized => "300006",
757 BaseError::HttpCircuitBreakerOpen(_) => "300007",
758 BaseError::HttpResponseTooLarge { .. } => "300008",
759 BaseError::UpstreamUnavailable(_) => "300009",
760 BaseError::TokenKeyInvalid(_) => "400001",
762 BaseError::TokenGenerateFailed(_) => "400002",
763 BaseError::TokenVerifyFailed(_) => "400003",
764 BaseError::TokenParseFailed(_) => "400004",
765 BaseError::TokenExpired => "400005",
766 BaseError::TokenTypeInvalid(_) => "400006",
767 BaseError::TokenRevoked => "400007",
768 BaseError::TokenRevocationStateInvalid(_) => "400008",
769 BaseError::AuthorizationStale => "400009",
770 BaseError::AuthorizationVersionInvalid => "400010",
771 BaseError::AuthorizationCheckUnavailable => "400011",
772 BaseError::JsonSerializeFailed(_) => "500001",
774 BaseError::JsonDeserializeFailed(_) => "500002",
775 BaseError::InvalidFieldType(_, _) => "600001",
777 BaseError::InvalidEnumValue(_, _) => "600002",
778 BaseError::StringTooLong(_, _, _) => "600003",
779 BaseError::InvalidJsonFormat(_, _) => "600004",
780 BaseError::ValidationFailed(_, _) => "600005",
781 BaseError::FieldRequired(_) => "600006",
782 BaseError::FieldNotFound(_, _) => "600007",
783 BaseError::FieldPermissionDenied(_, _, _) => "600008",
784 BaseError::ActionNotFound(_) => "700001",
786 BaseError::PermissionDenied(_) => "700002",
787 BaseError::Unauthorized(_) => "700003",
788 BaseError::ParamMissing(_) => "700004",
789 BaseError::ParamInvalid(_, _) => "700005",
790 BaseError::RecordNotFound(_) => "700006",
791 BaseError::UserNotFound(_) => "700007",
792 BaseError::InvalidPassword => "700008",
793 BaseError::TableDefinitionNotSet => "700009",
794 #[cfg(feature = "token")]
795 BaseError::StepUpRequired(_) => "700010",
796 BaseError::RateLimitExceeded { .. } => "700011",
797 BaseError::SecondFactorRequired => "700012",
798 BaseError::ConfigError(_) => "900001",
800 BaseError::IoError(_) => "900002",
801 BaseError::Unknown(_) => "999999",
802 }
803 }
804
805 pub fn category(&self) -> ErrorCategory {
815 use ErrorCategory as C;
816 match self {
817 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
819 BaseError::PluginCircularDependency(_) => C::Client,
820 BaseError::PluginDependencyMissing(_, _) => C::Client,
821 BaseError::PluginConfigInvalid(_, _) => C::Client,
822 BaseError::PluginNotFound(_)
823 | BaseError::PluginRegisterFailed(_, _)
824 | BaseError::PluginInitFailed(_, _)
825 | BaseError::PluginShutdownFailed(_, _)
826 | BaseError::PluginLifecycleFailed { .. } => C::Server,
827 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
830 C::Transient
831 }
832 BaseError::MissingWhereClause(_) => C::Client,
833 BaseError::DatabaseAlreadyInitialized
834 | BaseError::DatabaseNotInitialized
835 | BaseError::DatabaseInitFailed(_) => C::Server,
836 BaseError::DatabaseQueryFailed(_)
838 | BaseError::DatabaseExecuteFailed(_)
839 | BaseError::DatabaseTransactionFailed(_) => C::Server,
840 BaseError::RedisConnectionFailed(_) => C::Transient,
842 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
843 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
844 match source.category() {
845 yang_db::DbErrorCategory::Transient => C::Transient,
846 yang_db::DbErrorCategory::Conflict => C::Conflict,
847 yang_db::DbErrorCategory::Client => C::Client,
848 yang_db::DbErrorCategory::NotFound => C::NotFound,
849 yang_db::DbErrorCategory::Server => C::Server,
850 _ => C::Server,
851 }
852 }
853 BaseError::HttpClientCreateFailed(_)
855 | BaseError::HttpClientNotInitialized
856 | BaseError::HttpClientAlreadyInitialized => C::Client,
857 BaseError::HttpResponseParseFailed(_) => C::Client,
859 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
860 BaseError::UpstreamUnavailable(_) => C::Transient,
862 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
864 BaseError::HttpResponseTooLarge { .. } => C::Server,
866 BaseError::TokenKeyInvalid(_)
868 | BaseError::TokenGenerateFailed(_)
869 | BaseError::TokenTypeInvalid(_)
870 | BaseError::TokenParseFailed(_) => C::Client,
871 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
872 C::Auth
873 }
874 BaseError::TokenRevocationStateInvalid(_) => C::Server,
875 BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
876 BaseError::AuthorizationCheckUnavailable => C::Transient,
877 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
879 BaseError::InvalidFieldType(_, _)
881 | BaseError::InvalidEnumValue(_, _)
882 | BaseError::StringTooLong(_, _, _)
883 | BaseError::InvalidJsonFormat(_, _)
884 | BaseError::ValidationFailed(_, _)
885 | BaseError::FieldRequired(_)
886 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
887 BaseError::FieldNotFound(_, _) => C::NotFound,
888 BaseError::Unauthorized(_)
890 | BaseError::PermissionDenied(_)
891 | BaseError::SecondFactorRequired => C::Auth,
892 BaseError::ParamMissing(_)
893 | BaseError::ParamInvalid(_, _)
894 | BaseError::RateLimitExceeded { .. } => C::Client,
895 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
896 BaseError::InvalidPassword => C::Auth,
897 BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
898 #[cfg(feature = "token")]
899 BaseError::StepUpRequired(_) => C::Client,
900 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
902 }
903 }
904
905 pub fn is_retryable(&self) -> bool {
907 self.category() == ErrorCategory::Transient
908 }
909
910 pub fn is_client_error(&self) -> bool {
916 matches!(
917 self.category(),
918 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
919 )
920 }
921
922 pub fn is_server_error(&self) -> bool {
928 matches!(
929 self.category(),
930 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
931 )
932 }
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938
939 #[test]
940 fn test_not_ready_code_is_stable() {
941 assert_eq!(NOT_READY_CODE, 900001);
942 }
943
944 #[test]
945 fn test_error_codes_plugin() {
946 assert_eq!(
947 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
948 100001
949 );
950 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
951 assert_eq!(
952 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
953 100003
954 );
955 assert_eq!(
956 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
957 100004
958 );
959 assert_eq!(
960 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
961 100005
962 );
963 assert_eq!(
964 BaseError::PluginCircularDependency("test".to_string()).code(),
965 100006
966 );
967 assert_eq!(
968 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
969 100007
970 );
971 assert_eq!(
972 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
973 100008
974 );
975 }
976
977 #[test]
978 fn test_error_codes_database() {
979 assert_eq!(
980 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
981 "reason".to_string()
982 ))
983 .code(),
984 200001
985 );
986 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
987 assert_eq!(
988 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
989 .code(),
990 200003
991 );
992 assert_eq!(
993 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
994 .code(),
995 200004
996 );
997 assert_eq!(
998 BaseError::DatabaseInitFailed("reason".to_string()).code(),
999 200005
1000 );
1001 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
1002 assert_eq!(
1003 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
1004 "reason".to_string()
1005 ))
1006 .code(),
1007 200009
1008 );
1009 }
1010
1011 #[cfg(feature = "http")]
1012 #[test]
1013 fn test_error_codes_http() {
1014 assert_eq!(
1016 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
1017 300003
1018 );
1019 assert_eq!(BaseError::HttpTimeout.code(), 300004);
1020 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
1021 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
1022 }
1023
1024 #[cfg(feature = "token")]
1025 #[test]
1026 fn test_error_codes_token() {
1027 assert_eq!(
1028 BaseError::TokenKeyInvalid("reason".to_string()).code(),
1029 400001
1030 );
1031 assert_eq!(
1032 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
1033 jsonwebtoken::errors::ErrorKind::InvalidToken
1034 ))
1035 .code(),
1036 400002
1037 );
1038 assert_eq!(
1039 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
1040 jsonwebtoken::errors::ErrorKind::InvalidToken
1041 ))
1042 .code(),
1043 400003
1044 );
1045 assert_eq!(
1046 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
1047 jsonwebtoken::errors::ErrorKind::InvalidToken
1048 ))
1049 .code(),
1050 400004
1051 );
1052 assert_eq!(BaseError::TokenExpired.code(), 400005);
1053 assert_eq!(
1054 BaseError::TokenTypeInvalid("reason".to_string()).code(),
1055 400006
1056 );
1057 }
1058
1059 #[test]
1060 fn test_error_codes_serialization() {
1061 assert_eq!(
1062 BaseError::JsonSerializeFailed("reason".to_string()).code(),
1063 500001
1064 );
1065 assert_eq!(
1066 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
1067 500002
1068 );
1069 }
1070
1071 #[test]
1072 fn test_error_codes_field_validation() {
1073 assert_eq!(
1074 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
1075 600001
1076 );
1077 assert_eq!(
1078 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1079 600002
1080 );
1081 assert_eq!(
1082 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1083 600003
1084 );
1085 assert_eq!(
1086 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1087 600004
1088 );
1089 assert_eq!(
1090 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1091 600005
1092 );
1093 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1094 assert_eq!(
1095 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1096 600007
1097 );
1098 assert_eq!(
1099 BaseError::FieldPermissionDenied(
1100 "table".to_string(),
1101 "field".to_string(),
1102 "reason".to_string()
1103 )
1104 .code(),
1105 600008
1106 );
1107 }
1108
1109 #[test]
1110 fn test_error_codes_action_system() {
1111 assert_eq!(
1112 BaseError::ActionNotFound("test_action".to_string()).code(),
1113 700001
1114 );
1115 assert_eq!(
1116 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1117 700002
1118 );
1119 assert_eq!(
1120 BaseError::Unauthorized("Token 无效".to_string()).code(),
1121 700003
1122 );
1123 assert_eq!(
1124 BaseError::ParamMissing("user_id".to_string()).code(),
1125 700004
1126 );
1127 assert_eq!(
1128 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1129 700005
1130 );
1131 assert_eq!(
1132 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1133 700006
1134 );
1135 assert_eq!(
1136 BaseError::UserNotFound("user_123".to_string()).code(),
1137 700007
1138 );
1139 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1140 assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1141 assert_eq!(
1142 BaseError::RateLimitExceeded {
1143 retry_after_seconds: 30
1144 }
1145 .code(),
1146 700011
1147 );
1148 assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
1149 assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
1150 }
1151
1152 #[test]
1153 fn test_error_codes_general() {
1154 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1155 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1156 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1157 }
1158
1159 #[test]
1160 fn test_all_error_codes_are_nonzero() {
1161 let errors: Vec<BaseError> = vec![
1163 BaseError::PluginNotFound("test".to_string()),
1164 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1165 BaseError::HttpTimeout,
1166 BaseError::TokenExpired,
1167 BaseError::JsonSerializeFailed("test".to_string()),
1168 BaseError::FieldRequired("test".to_string()),
1169 BaseError::ActionNotFound("test".to_string()),
1170 BaseError::PermissionDenied("test".to_string()),
1171 BaseError::Unauthorized("test".to_string()),
1172 BaseError::ParamMissing("test".to_string()),
1173 BaseError::RecordNotFound("test".to_string()),
1174 BaseError::UserNotFound("test".to_string()),
1175 BaseError::InvalidPassword,
1176 BaseError::TableDefinitionNotSet,
1177 BaseError::RateLimitExceeded {
1178 retry_after_seconds: 30,
1179 },
1180 BaseError::Unknown("test".to_string()),
1181 ];
1182
1183 for error in errors {
1184 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1185 }
1186 }
1187
1188 #[test]
1190 fn test_database_error_source_chain() {
1191 use std::error::Error;
1192
1193 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1194 let base_err = BaseError::DatabaseQueryFailed(db_err);
1195
1196 let source = base_err.source();
1198 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1199 }
1200
1201 #[test]
1203 fn test_from_db_error_preserves_source() {
1204 use std::error::Error;
1205
1206 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1207 let base_err: BaseError = db_err.into();
1208
1209 assert!(base_err.source().is_some());
1211 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1212 }
1213
1214 #[test]
1215 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1216 use std::error::Error;
1217
1218 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1219 "connection refused".into(),
1220 ));
1221 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1222 "WRONGTYPE".into(),
1223 ));
1224
1225 assert_eq!(connection.code(), 210001);
1226 assert_eq!(operation.code(), 210004);
1227 assert!(connection.source().is_some());
1228 assert!(operation.source().is_some());
1229 }
1230
1231 #[test]
1232 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1233 use std::error::Error;
1234
1235 let error = BaseError::PluginLifecycleFailed {
1236 plugin: "audit".into(),
1237 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1238 source: Box::new(std::io::Error::other("flush failed")),
1239 };
1240
1241 assert_eq!(error.code(), 100008);
1242 assert_eq!(error.code_str(), "100008");
1243 assert!(error.to_string().contains("audit"));
1244 assert!(error.to_string().contains("shutdown"));
1245 assert!(error.source().is_some());
1246 }
1247
1248 #[test]
1250 fn test_code_str_matches_code() {
1251 let samples: Vec<BaseError> = vec![
1253 BaseError::PluginNotFound("p".into()),
1254 BaseError::PluginLifecycleFailed {
1255 plugin: "p".into(),
1256 stage: crate::plugin::PluginLifecycleStage::Initialize,
1257 source: Box::new(std::io::Error::other("init")),
1258 },
1259 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1260 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1261 BaseError::DatabaseNotInitialized,
1262 BaseError::RedisNotInitialized,
1263 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1264 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1265 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1266 BaseError::HttpTimeout,
1267 BaseError::TokenExpired,
1268 BaseError::TokenRevoked,
1269 BaseError::TokenRevocationStateInvalid("invalid".into()),
1270 BaseError::AuthorizationStale,
1271 BaseError::AuthorizationVersionInvalid,
1272 BaseError::AuthorizationCheckUnavailable,
1273 BaseError::JsonSerializeFailed("s".into()),
1274 BaseError::FieldNotFound("t".into(), "f".into()),
1275 BaseError::ParamInvalid("k".into(), "r".into()),
1276 BaseError::TableDefinitionNotSet,
1277 BaseError::RateLimitExceeded {
1278 retry_after_seconds: 30,
1279 },
1280 BaseError::SecondFactorRequired,
1281 BaseError::ConfigError("c".into()),
1282 BaseError::Unknown("u".into()),
1283 ];
1284 for err in samples {
1285 let code = err.code();
1286 let code_str = err.code_str();
1287 assert_eq!(
1288 code_str.parse::<i32>().unwrap(),
1289 code,
1290 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1291 code_str,
1292 code,
1293 err
1294 );
1295 }
1296 }
1297
1298 #[test]
1300 fn test_error_category_coverage() {
1301 assert_eq!(
1303 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1304 ErrorCategory::Client
1305 );
1306 assert_eq!(
1307 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1308 ErrorCategory::Client
1309 );
1310 assert_eq!(
1312 BaseError::Unauthorized("u".into()).category(),
1313 ErrorCategory::Auth
1314 );
1315 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1316 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1317 assert_eq!(
1318 BaseError::SecondFactorRequired.category(),
1319 ErrorCategory::Auth
1320 );
1321 assert_eq!(
1323 BaseError::RecordNotFound("r".into()).category(),
1324 ErrorCategory::NotFound
1325 );
1326 assert_eq!(
1327 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1328 ErrorCategory::NotFound
1329 );
1330 assert_eq!(
1332 BaseError::PluginAlreadyRegistered("p".into()).category(),
1333 ErrorCategory::Conflict
1334 );
1335 assert_eq!(
1337 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1338 .category(),
1339 ErrorCategory::Transient
1340 );
1341 assert_eq!(
1342 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1343 .category(),
1344 ErrorCategory::Transient
1345 );
1346 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1347 assert_eq!(
1349 BaseError::Unknown("u".into()).category(),
1350 ErrorCategory::Server
1351 );
1352 assert_eq!(
1353 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1354 ErrorCategory::Server
1355 );
1356 }
1357
1358 #[test]
1360 fn test_is_retryable() {
1361 assert!(
1362 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1363 .is_retryable()
1364 );
1365 assert!(BaseError::HttpTimeout.is_retryable());
1366 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1367 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1368 assert!(!BaseError::Unknown("u".into()).is_retryable());
1369 }
1370
1371 #[test]
1373 fn test_is_client_error() {
1374 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1375 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1376 assert!(BaseError::TokenExpired.is_client_error());
1377 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1378 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1379 assert!(
1380 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1381 .is_client_error()
1382 );
1383 assert!(!BaseError::Unknown("u".into()).is_client_error());
1384 }
1385
1386 #[test]
1388 fn test_is_server_error() {
1389 assert!(BaseError::Unknown("u".into()).is_server_error());
1390 assert!(
1391 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1392 .is_server_error()
1393 );
1394 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1395 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1396 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1397 }
1398
1399 #[test]
1401 fn mysql_duplicate_entry_maps_to_param_invalid_naming_the_key() {
1402 let error = BaseError::from(yang_db::DbError::ConstraintError(
1406 "Duplicate entry 'payment_currency' for key 'source_key'".to_string(),
1407 ));
1408 match error {
1409 BaseError::ParamInvalid(field, message) => {
1410 assert_eq!(field, "source_key", "要点名冲突的键");
1411 assert!(!message.is_empty());
1412 }
1413 other => panic!("唯一键冲突应映射为 ParamInvalid,实际: {other:?}"),
1414 }
1415 }
1416
1417 #[test]
1419 fn qualified_mysql_key_name_keeps_only_the_last_segment() {
1420 assert_eq!(
1421 duplicate_key_field(
1422 "Duplicate entry 'x' for key 'yang_system.feishu_datasource.source_key'"
1423 ),
1424 Some("source_key".to_string())
1425 );
1426 }
1427
1428 #[test]
1430 fn postgres_unique_violation_maps_to_param_invalid() {
1431 let error = BaseError::from(yang_db::DbError::ConstraintError(
1432 "duplicate key value violates unique constraint \"feishu_option_option_id_key\""
1433 .to_string(),
1434 ));
1435 match error {
1436 BaseError::ParamInvalid(field, _) => assert_eq!(field, "feishu_option_option_id_key"),
1437 other => panic!("PG 唯一约束冲突应映射为 ParamInvalid,实际: {other:?}"),
1438 }
1439 }
1440
1441 #[test]
1446 fn other_constraint_errors_keep_their_own_mapping() {
1447 for message in [
1448 "Cannot add or update a child row: a foreign key constraint fails",
1449 "Column 'title' cannot be null",
1450 "Check constraint 'positive_amount' is violated",
1451 ] {
1452 let error = BaseError::from(yang_db::DbError::ConstraintError(message.to_string()));
1453 assert!(
1454 !matches!(error, BaseError::ParamInvalid(_, _)),
1455 "{message:?} 不该被当成参数非法,实际: {error:?}"
1456 );
1457 }
1458 }
1459
1460 #[test]
1462 fn duplicate_key_field_returns_none_for_unrecognised_messages() {
1463 assert_eq!(duplicate_key_field(""), None);
1464 assert_eq!(
1465 duplicate_key_field("Duplicate entry 'x'"),
1466 None,
1467 "缺 for key 段就该放弃提取,而不是编一个名字出来"
1468 );
1469 assert_eq!(duplicate_key_field("some other db error"), None);
1470 }
1471}