1use thiserror::Error;
21
22pub type Result<T, E = BaseError> = std::result::Result<T, E>;
27
28#[derive(Debug, Error)]
36#[non_exhaustive]
37pub enum BaseError {
38 #[error("插件已注册: {0}")]
41 PluginAlreadyRegistered(String),
42
43 #[error("插件未找到: {0}")]
45 PluginNotFound(String),
46
47 #[error("插件注册失败 [{0}]: {1}")]
49 PluginRegisterFailed(String, String),
50
51 #[error("插件初始化失败 [{0}]: {1}")]
53 PluginInitFailed(String, String),
54
55 #[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
57 PluginDependencyMissing(String, String),
58
59 #[error("插件循环依赖: {0}")]
61 PluginCircularDependency(String),
62
63 #[error("插件配置无效 [{0}]: {1}")]
65 PluginConfigInvalid(String, String),
66
67 #[error("插件关闭失败 [{0}]: {1}")]
69 PluginShutdownFailed(String, String),
70
71 #[error("插件生命周期失败 [{plugin}] ({stage}): {source}")]
73 PluginLifecycleFailed {
74 plugin: String,
76 stage: crate::plugin::PluginLifecycleStage,
78 #[source]
80 source: crate::plugin::PluginError,
81 },
82
83 #[error("数据库连接失败 [DbError]: {0}")]
86 DatabaseConnectionFailed(#[source] yang_db::DbError),
87
88 #[error("数据库连接失败 [DbError]: {0}")]
93 DatabaseConnectionDbError(#[source] yang_db::DbError),
94
95 #[error("数据库已初始化")]
97 DatabaseAlreadyInitialized,
98
99 #[error("数据库查询失败: {0}")]
101 DatabaseQueryFailed(#[source] yang_db::DbError),
102
103 #[error("数据库执行失败: {0}")]
105 DatabaseExecuteFailed(#[source] yang_db::DbError),
106
107 #[error("数据库初始化失败: {0}")]
109 DatabaseInitFailed(String),
110
111 #[error("数据库迁移失败 [{0}]: {1}")]
113 DatabaseMigrationFailed(String, String),
114
115 #[error("迁移失败 [{0}] v{1}: {2}")]
117 MigrationFailed(String, String, String),
118
119 #[error("迁移执行失败 [{module}] v{version} checksum={checksum}: {source}")]
121 MigrationExecutionFailed {
122 module: String,
124 version: String,
126 checksum: String,
128 #[source]
130 source: yang_db::DbError,
131 },
132
133 #[error("迁移校验和不一致 [{module}] v{version}: expected={expected}, actual={actual:?}")]
135 MigrationChecksumMismatch {
136 module: String,
138 version: String,
140 expected: String,
142 actual: Option<String>,
144 },
145
146 #[error("迁移正在执行 [{module}] v{version}")]
148 MigrationInProgress {
149 module: String,
151 version: String,
153 },
154
155 #[error("数据库未初始化")]
157 DatabaseNotInitialized,
158
159 #[error("数据库事务失败: {0}")]
161 DatabaseTransactionFailed(#[source] yang_db::DbError),
162
163 #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
169 MissingWhereClause(String),
170
171 #[error("Redis 连接失败: {0}")]
174 RedisConnectionFailed(#[source] yang_db::DbError),
175
176 #[error("Redis 已初始化")]
178 RedisAlreadyInitialized,
179
180 #[error("Redis 未初始化")]
182 RedisNotInitialized,
183
184 #[error("Redis 操作失败: {0}")]
186 RedisOperationFailed(#[source] yang_db::DbError),
187
188 #[error("Redis 操作失败: {0}")]
190 RedisOperationDbError(#[source] yang_db::DbError),
191
192 #[cfg(feature = "http")]
195 #[error("HTTP 客户端创建失败: {0}")]
196 HttpClientCreateFailed(#[source] reqwest::Error),
197
198 #[cfg(not(feature = "http"))]
200 #[error("HTTP 客户端创建失败: {0}")]
201 HttpClientCreateFailed(String),
202
203 #[cfg(feature = "http")]
205 #[error("HTTP 请求失败: {0}")]
206 HttpRequestFailed(#[source] reqwest::Error),
207
208 #[cfg(not(feature = "http"))]
210 #[error("HTTP 请求失败: {0}")]
211 HttpRequestFailed(String),
212
213 #[error("HTTP 响应解析失败: {0}")]
215 HttpResponseParseFailed(String),
216
217 #[error("HTTP 请求超时")]
219 HttpTimeout,
220
221 #[error("HTTP 客户端已初始化")]
223 HttpClientAlreadyInitialized,
224
225 #[error("HTTP 客户端未初始化")]
227 HttpClientNotInitialized,
228
229 #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
231 HttpCircuitBreakerOpen(String),
232
233 #[error("Token 密钥无效: {0}")]
236 TokenKeyInvalid(String),
237
238 #[cfg(feature = "token")]
240 #[error("Token 生成失败: {0}")]
241 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
242
243 #[cfg(not(feature = "token"))]
245 #[error("Token 生成失败: {0}")]
246 TokenGenerateFailed(String),
247
248 #[cfg(feature = "token")]
250 #[error("Token 验证失败: {0}")]
251 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
252
253 #[cfg(not(feature = "token"))]
255 #[error("Token 验证失败: {0}")]
256 TokenVerifyFailed(String),
257
258 #[cfg(feature = "token")]
260 #[error("Token 解析失败: {0}")]
261 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
262
263 #[cfg(not(feature = "token"))]
265 #[error("Token 解析失败: {0}")]
266 TokenParseFailed(String),
267
268 #[error("Token 已过期")]
270 TokenExpired,
271
272 #[error("Token 已被撤销")]
274 TokenRevoked,
275
276 #[error("Token 类型无效: {0}")]
278 TokenTypeInvalid(String),
279
280 #[error("JSON 序列化失败: {0}")]
283 JsonSerializeFailed(String),
284
285 #[error("JSON 反序列化失败: {0}")]
287 JsonDeserializeFailed(String),
288
289 #[error("字段类型无效 [{0}]: {1}")]
292 InvalidFieldType(String, String),
293
294 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
296 InvalidEnumValue(String, String),
297
298 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
300 StringTooLong(String, usize, usize),
301
302 #[error("JSON 格式无效 [{0}]: {1}")]
304 InvalidJsonFormat(String, String),
305
306 #[error("验证失败 [{0}]: {1}")]
308 ValidationFailed(String, String),
309
310 #[error("字段必填: {0}")]
312 FieldRequired(String),
313
314 #[error("字段未找到 [表: {0}]: {1}")]
316 FieldNotFound(String, String),
317
318 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
320 FieldPermissionDenied(String, String, String),
321
322 #[error("Action 未找到: {0}")]
325 ActionNotFound(String),
326
327 #[error("权限被拒绝: {0}")]
329 PermissionDenied(String),
330
331 #[error("未授权: {0}")]
333 Unauthorized(String),
334
335 #[error("参数缺失: {0}")]
337 ParamMissing(String),
338
339 #[error("参数无效 [{0}]: {1}")]
341 ParamInvalid(String, String),
342
343 #[error("记录未找到: {0}")]
345 RecordNotFound(String),
346
347 #[error("用户未找到: {0}")]
349 UserNotFound(String),
350
351 #[error("密码无效")]
353 InvalidPassword,
354
355 #[error("表配置未设置")]
357 TableConfigNotSet,
358
359 #[error("配置错误: {0}")]
362 ConfigError(String),
363
364 #[error("IO 错误: {0}")]
366 IoError(String),
367
368 #[error("未知错误: {0}")]
370 Unknown(String),
371}
372
373#[allow(unreachable_patterns)]
385impl From<yang_db::DbError> for BaseError {
386 fn from(err: yang_db::DbError) -> Self {
387 use yang_db::DbError as D;
388 match &err {
389 D::QueryError(_)
391 | D::TableNotFound(_)
392 | D::TypeConversionError(_)
393 | D::DeserializationError(_)
394 | D::UnsupportedOperator(_)
395 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
396
397 D::ConstraintError(_)
399 | D::SqlSyntaxError(_)
400 | D::MissingWhereClause
401 | D::MissingGroupByClause
402 | D::InvalidArgument(_)
403 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
404
405 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
407
408 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
410
411 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
413
414 D::RedisCommandError(_)
416 | D::RedisPoolError(_)
417 | D::RedisTypeConversionError(_)
418 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
419
420 _ => BaseError::DatabaseQueryFailed(err),
422 }
423 }
424}
425
426impl From<std::io::Error> for BaseError {
428 fn from(err: std::io::Error) -> Self {
429 BaseError::IoError(err.to_string())
430 }
431}
432
433impl From<serde_json::Error> for BaseError {
435 fn from(err: serde_json::Error) -> Self {
436 if err.is_syntax() || err.is_data() || err.is_eof() {
437 BaseError::JsonDeserializeFailed(err.to_string())
438 } else {
439 BaseError::JsonSerializeFailed(err.to_string())
440 }
441 }
442}
443
444#[cfg(feature = "http")]
446impl From<reqwest::Error> for BaseError {
447 fn from(err: reqwest::Error) -> Self {
448 if err.is_timeout() {
449 BaseError::HttpTimeout
450 } else {
451 BaseError::HttpRequestFailed(err)
455 }
456 }
457}
458
459#[cfg(feature = "token")]
466impl From<jsonwebtoken::errors::Error> for BaseError {
467 fn from(err: jsonwebtoken::errors::Error) -> Self {
468 use jsonwebtoken::errors::ErrorKind;
469 match err.kind() {
470 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
471 ErrorKind::InvalidToken
472 | ErrorKind::InvalidSignature
473 | ErrorKind::InvalidIssuer
474 | ErrorKind::InvalidAudience
475 | ErrorKind::InvalidSubject
476 | ErrorKind::InvalidAlgorithm
477 | ErrorKind::MissingAlgorithm
478 | ErrorKind::ImmatureSignature
479 | ErrorKind::MissingRequiredClaim(_)
480 | ErrorKind::InvalidEcdsaKey
481 | ErrorKind::InvalidRsaKey(_)
482 | ErrorKind::InvalidKeyFormat
483 | ErrorKind::RsaFailedSigning
484 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
485 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
487 BaseError::TokenParseFailed(err)
488 }
489 _ => BaseError::TokenVerifyFailed(err),
491 }
492 }
493}
494
495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503#[non_exhaustive]
504pub enum ErrorCategory {
505 Client,
507 Auth,
509 NotFound,
511 Conflict,
513 Transient,
518 Server,
520}
521
522impl BaseError {
523 pub fn code(&self) -> i32 {
552 match self {
553 BaseError::PluginAlreadyRegistered(_) => 100001,
555 BaseError::PluginNotFound(_) => 100002,
556 BaseError::PluginRegisterFailed(_, _) => 100003,
557 BaseError::PluginInitFailed(_, _) => 100004,
558 BaseError::PluginDependencyMissing(_, _) => 100005,
559 BaseError::PluginCircularDependency(_) => 100006,
560 BaseError::PluginConfigInvalid(_, _) => 100007,
561 BaseError::PluginShutdownFailed(_, _) => 100008,
562 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
563 crate::plugin::PluginLifecycleStage::Register => 100003,
564 crate::plugin::PluginLifecycleStage::Initialize => 100004,
565 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
566 },
567
568 BaseError::DatabaseConnectionFailed(_) => 200001,
570 BaseError::DatabaseConnectionDbError(_) => 200011,
571 BaseError::DatabaseAlreadyInitialized => 200002,
572 BaseError::DatabaseQueryFailed(_) => 200003,
573 BaseError::DatabaseExecuteFailed(_) => 200004,
574 BaseError::DatabaseInitFailed(_) => 200005,
575 BaseError::DatabaseMigrationFailed(_, _) => 200006,
576 BaseError::MigrationFailed(_, _, _) => 200007,
577 BaseError::MigrationExecutionFailed { .. }
578 | BaseError::MigrationChecksumMismatch { .. }
579 | BaseError::MigrationInProgress { .. } => 200007,
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
600 BaseError::TokenKeyInvalid(_) => 400001,
602 BaseError::TokenGenerateFailed(_) => 400002,
603 BaseError::TokenVerifyFailed(_) => 400003,
604 BaseError::TokenParseFailed(_) => 400004,
605 BaseError::TokenExpired => 400005,
606 BaseError::TokenTypeInvalid(_) => 400006,
607 BaseError::TokenRevoked => 400007,
608
609 BaseError::JsonSerializeFailed(_) => 500001,
611 BaseError::JsonDeserializeFailed(_) => 500002,
612
613 BaseError::InvalidFieldType(_, _) => 600001,
615 BaseError::InvalidEnumValue(_, _) => 600002,
616 BaseError::StringTooLong(_, _, _) => 600003,
617 BaseError::InvalidJsonFormat(_, _) => 600004,
618 BaseError::ValidationFailed(_, _) => 600005,
619 BaseError::FieldRequired(_) => 600006,
620 BaseError::FieldNotFound(_, _) => 600007,
621 BaseError::FieldPermissionDenied(_, _, _) => 600008,
622
623 BaseError::ActionNotFound(_) => 700001,
625 BaseError::PermissionDenied(_) => 700002,
626 BaseError::Unauthorized(_) => 700003,
627 BaseError::ParamMissing(_) => 700004,
628 BaseError::ParamInvalid(_, _) => 700005,
629 BaseError::RecordNotFound(_) => 700006,
630 BaseError::UserNotFound(_) => 700007,
631 BaseError::InvalidPassword => 700008,
632 BaseError::TableConfigNotSet => 700009,
633
634 BaseError::ConfigError(_) => 900001,
636 BaseError::IoError(_) => 900002,
637 BaseError::Unknown(_) => 999999,
638 }
639 }
640
641 pub fn code_str(&self) -> &'static str {
648 match self {
649 BaseError::PluginAlreadyRegistered(_) => "100001",
651 BaseError::PluginNotFound(_) => "100002",
652 BaseError::PluginRegisterFailed(_, _) => "100003",
653 BaseError::PluginInitFailed(_, _) => "100004",
654 BaseError::PluginDependencyMissing(_, _) => "100005",
655 BaseError::PluginCircularDependency(_) => "100006",
656 BaseError::PluginConfigInvalid(_, _) => "100007",
657 BaseError::PluginShutdownFailed(_, _) => "100008",
658 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
659 crate::plugin::PluginLifecycleStage::Register => "100003",
660 crate::plugin::PluginLifecycleStage::Initialize => "100004",
661 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
662 },
663 BaseError::DatabaseConnectionFailed(_) => "200001",
665 BaseError::DatabaseConnectionDbError(_) => "200011",
666 BaseError::DatabaseAlreadyInitialized => "200002",
667 BaseError::DatabaseQueryFailed(_) => "200003",
668 BaseError::DatabaseExecuteFailed(_) => "200004",
669 BaseError::DatabaseInitFailed(_) => "200005",
670 BaseError::DatabaseMigrationFailed(_, _) => "200006",
671 BaseError::MigrationFailed(_, _, _) => "200007",
672 BaseError::MigrationExecutionFailed { .. }
673 | BaseError::MigrationChecksumMismatch { .. }
674 | BaseError::MigrationInProgress { .. } => "200007",
675 BaseError::DatabaseNotInitialized => "200008",
676 BaseError::DatabaseTransactionFailed(_) => "200009",
677 BaseError::MissingWhereClause(_) => "200010",
678 BaseError::RedisConnectionFailed(_) => "210001",
680 BaseError::RedisAlreadyInitialized => "210002",
681 BaseError::RedisNotInitialized => "210003",
682 BaseError::RedisOperationFailed(_) => "210004",
683 BaseError::RedisOperationDbError(_) => "210011",
684 BaseError::HttpClientCreateFailed(_) => "300001",
686 BaseError::HttpRequestFailed(_) => "300002",
687 BaseError::HttpResponseParseFailed(_) => "300003",
688 BaseError::HttpTimeout => "300004",
689 BaseError::HttpClientAlreadyInitialized => "300005",
690 BaseError::HttpClientNotInitialized => "300006",
691 BaseError::HttpCircuitBreakerOpen(_) => "300007",
692 BaseError::TokenKeyInvalid(_) => "400001",
694 BaseError::TokenGenerateFailed(_) => "400002",
695 BaseError::TokenVerifyFailed(_) => "400003",
696 BaseError::TokenParseFailed(_) => "400004",
697 BaseError::TokenExpired => "400005",
698 BaseError::TokenTypeInvalid(_) => "400006",
699 BaseError::TokenRevoked => "400007",
700 BaseError::JsonSerializeFailed(_) => "500001",
702 BaseError::JsonDeserializeFailed(_) => "500002",
703 BaseError::InvalidFieldType(_, _) => "600001",
705 BaseError::InvalidEnumValue(_, _) => "600002",
706 BaseError::StringTooLong(_, _, _) => "600003",
707 BaseError::InvalidJsonFormat(_, _) => "600004",
708 BaseError::ValidationFailed(_, _) => "600005",
709 BaseError::FieldRequired(_) => "600006",
710 BaseError::FieldNotFound(_, _) => "600007",
711 BaseError::FieldPermissionDenied(_, _, _) => "600008",
712 BaseError::ActionNotFound(_) => "700001",
714 BaseError::PermissionDenied(_) => "700002",
715 BaseError::Unauthorized(_) => "700003",
716 BaseError::ParamMissing(_) => "700004",
717 BaseError::ParamInvalid(_, _) => "700005",
718 BaseError::RecordNotFound(_) => "700006",
719 BaseError::UserNotFound(_) => "700007",
720 BaseError::InvalidPassword => "700008",
721 BaseError::TableConfigNotSet => "700009",
722 BaseError::ConfigError(_) => "900001",
724 BaseError::IoError(_) => "900002",
725 BaseError::Unknown(_) => "999999",
726 }
727 }
728
729 pub fn category(&self) -> ErrorCategory {
739 use ErrorCategory as C;
740 match self {
741 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
743 BaseError::PluginCircularDependency(_) => C::Client,
744 BaseError::PluginDependencyMissing(_, _) => C::Client,
745 BaseError::PluginConfigInvalid(_, _) => C::Client,
746 BaseError::PluginNotFound(_)
747 | BaseError::PluginRegisterFailed(_, _)
748 | BaseError::PluginInitFailed(_, _)
749 | BaseError::PluginShutdownFailed(_, _)
750 | BaseError::PluginLifecycleFailed { .. } => C::Server,
751 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
754 C::Transient
755 }
756 BaseError::MissingWhereClause(_)
757 | BaseError::DatabaseMigrationFailed(_, _)
758 | BaseError::MigrationFailed(_, _, _)
759 | BaseError::MigrationExecutionFailed { .. }
760 | BaseError::MigrationChecksumMismatch { .. }
761 | BaseError::MigrationInProgress { .. } => C::Client,
762 BaseError::DatabaseAlreadyInitialized
763 | BaseError::DatabaseNotInitialized
764 | BaseError::DatabaseInitFailed(_) => C::Server,
765 BaseError::DatabaseQueryFailed(_)
767 | BaseError::DatabaseExecuteFailed(_)
768 | BaseError::DatabaseTransactionFailed(_) => C::Server,
769 BaseError::RedisConnectionFailed(_) => C::Transient,
771 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
772 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
773 match source.category() {
774 yang_db::DbErrorCategory::Transient => C::Transient,
775 yang_db::DbErrorCategory::Conflict => C::Conflict,
776 yang_db::DbErrorCategory::Client => C::Client,
777 yang_db::DbErrorCategory::NotFound => C::NotFound,
778 yang_db::DbErrorCategory::Server => C::Server,
779 _ => C::Server,
780 }
781 }
782 BaseError::HttpClientCreateFailed(_)
784 | BaseError::HttpClientNotInitialized
785 | BaseError::HttpClientAlreadyInitialized => C::Client,
786 BaseError::HttpResponseParseFailed(_) => C::Client,
788 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
789 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
791 BaseError::TokenKeyInvalid(_)
793 | BaseError::TokenGenerateFailed(_)
794 | BaseError::TokenTypeInvalid(_)
795 | BaseError::TokenParseFailed(_) => C::Client,
796 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
797 C::Auth
798 }
799 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
801 BaseError::InvalidFieldType(_, _)
803 | BaseError::InvalidEnumValue(_, _)
804 | BaseError::StringTooLong(_, _, _)
805 | BaseError::InvalidJsonFormat(_, _)
806 | BaseError::ValidationFailed(_, _)
807 | BaseError::FieldRequired(_)
808 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
809 BaseError::FieldNotFound(_, _) => C::NotFound,
810 BaseError::Unauthorized(_) | BaseError::PermissionDenied(_) => C::Auth,
812 BaseError::ParamMissing(_) | BaseError::ParamInvalid(_, _) => C::Client,
813 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
814 BaseError::InvalidPassword => C::Auth,
815 BaseError::ActionNotFound(_) | BaseError::TableConfigNotSet => C::NotFound,
816 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
818 }
819 }
820
821 pub fn is_retryable(&self) -> bool {
823 self.category() == ErrorCategory::Transient
824 }
825
826 pub fn is_client_error(&self) -> bool {
832 matches!(
833 self.category(),
834 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
835 )
836 }
837
838 pub fn is_server_error(&self) -> bool {
844 matches!(
845 self.category(),
846 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
847 )
848 }
849}
850
851#[cfg(test)]
852mod tests {
853 use super::*;
854
855 #[test]
856 fn test_error_codes_plugin() {
857 assert_eq!(
858 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
859 100001
860 );
861 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
862 assert_eq!(
863 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
864 100003
865 );
866 assert_eq!(
867 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
868 100004
869 );
870 assert_eq!(
871 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
872 100005
873 );
874 assert_eq!(
875 BaseError::PluginCircularDependency("test".to_string()).code(),
876 100006
877 );
878 assert_eq!(
879 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
880 100007
881 );
882 assert_eq!(
883 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
884 100008
885 );
886 }
887
888 #[test]
889 fn test_error_codes_database() {
890 assert_eq!(
891 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
892 "reason".to_string()
893 ))
894 .code(),
895 200001
896 );
897 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
898 assert_eq!(
899 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
900 .code(),
901 200003
902 );
903 assert_eq!(
904 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
905 .code(),
906 200004
907 );
908 assert_eq!(
909 BaseError::DatabaseInitFailed("reason".to_string()).code(),
910 200005
911 );
912 assert_eq!(
913 BaseError::DatabaseMigrationFailed("plugin".to_string(), "reason".to_string()).code(),
914 200006
915 );
916 assert_eq!(
917 BaseError::MigrationFailed(
918 "plugin".to_string(),
919 "v1".to_string(),
920 "reason".to_string()
921 )
922 .code(),
923 200007
924 );
925 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
926 assert_eq!(
927 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
928 "reason".to_string()
929 ))
930 .code(),
931 200009
932 );
933 }
934
935 #[cfg(feature = "http")]
936 #[test]
937 fn test_error_codes_http() {
938 assert_eq!(
940 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
941 300003
942 );
943 assert_eq!(BaseError::HttpTimeout.code(), 300004);
944 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
945 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
946 }
947
948 #[cfg(feature = "token")]
949 #[test]
950 fn test_error_codes_token() {
951 assert_eq!(
952 BaseError::TokenKeyInvalid("reason".to_string()).code(),
953 400001
954 );
955 assert_eq!(
956 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
957 jsonwebtoken::errors::ErrorKind::InvalidToken
958 ))
959 .code(),
960 400002
961 );
962 assert_eq!(
963 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
964 jsonwebtoken::errors::ErrorKind::InvalidToken
965 ))
966 .code(),
967 400003
968 );
969 assert_eq!(
970 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
971 jsonwebtoken::errors::ErrorKind::InvalidToken
972 ))
973 .code(),
974 400004
975 );
976 assert_eq!(BaseError::TokenExpired.code(), 400005);
977 assert_eq!(
978 BaseError::TokenTypeInvalid("reason".to_string()).code(),
979 400006
980 );
981 }
982
983 #[test]
984 fn test_error_codes_serialization() {
985 assert_eq!(
986 BaseError::JsonSerializeFailed("reason".to_string()).code(),
987 500001
988 );
989 assert_eq!(
990 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
991 500002
992 );
993 }
994
995 #[test]
996 fn test_error_codes_field_validation() {
997 assert_eq!(
998 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
999 600001
1000 );
1001 assert_eq!(
1002 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1003 600002
1004 );
1005 assert_eq!(
1006 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1007 600003
1008 );
1009 assert_eq!(
1010 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1011 600004
1012 );
1013 assert_eq!(
1014 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1015 600005
1016 );
1017 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1018 assert_eq!(
1019 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1020 600007
1021 );
1022 assert_eq!(
1023 BaseError::FieldPermissionDenied(
1024 "table".to_string(),
1025 "field".to_string(),
1026 "reason".to_string()
1027 )
1028 .code(),
1029 600008
1030 );
1031 }
1032
1033 #[test]
1034 fn test_error_codes_action_system() {
1035 assert_eq!(
1036 BaseError::ActionNotFound("test_action".to_string()).code(),
1037 700001
1038 );
1039 assert_eq!(
1040 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1041 700002
1042 );
1043 assert_eq!(
1044 BaseError::Unauthorized("Token 无效".to_string()).code(),
1045 700003
1046 );
1047 assert_eq!(
1048 BaseError::ParamMissing("user_id".to_string()).code(),
1049 700004
1050 );
1051 assert_eq!(
1052 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1053 700005
1054 );
1055 assert_eq!(
1056 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1057 700006
1058 );
1059 assert_eq!(
1060 BaseError::UserNotFound("user_123".to_string()).code(),
1061 700007
1062 );
1063 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1064 assert_eq!(BaseError::TableConfigNotSet.code(), 700009);
1065 }
1066
1067 #[test]
1068 fn test_error_codes_general() {
1069 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1070 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1071 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1072 }
1073
1074 #[test]
1075 fn test_all_error_codes_are_nonzero() {
1076 let errors: Vec<BaseError> = vec![
1078 BaseError::PluginNotFound("test".to_string()),
1079 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1080 BaseError::HttpTimeout,
1081 BaseError::TokenExpired,
1082 BaseError::JsonSerializeFailed("test".to_string()),
1083 BaseError::FieldRequired("test".to_string()),
1084 BaseError::ActionNotFound("test".to_string()),
1085 BaseError::PermissionDenied("test".to_string()),
1086 BaseError::Unauthorized("test".to_string()),
1087 BaseError::ParamMissing("test".to_string()),
1088 BaseError::RecordNotFound("test".to_string()),
1089 BaseError::UserNotFound("test".to_string()),
1090 BaseError::InvalidPassword,
1091 BaseError::TableConfigNotSet,
1092 BaseError::Unknown("test".to_string()),
1093 ];
1094
1095 for error in errors {
1096 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1097 }
1098 }
1099
1100 #[test]
1102 fn test_database_error_source_chain() {
1103 use std::error::Error;
1104
1105 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1106 let base_err = BaseError::DatabaseQueryFailed(db_err);
1107
1108 let source = base_err.source();
1110 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1111 }
1112
1113 #[test]
1115 fn test_from_db_error_preserves_source() {
1116 use std::error::Error;
1117
1118 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1119 let base_err: BaseError = db_err.into();
1120
1121 assert!(base_err.source().is_some());
1123 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1124 }
1125
1126 #[test]
1127 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1128 use std::error::Error;
1129
1130 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1131 "connection refused".into(),
1132 ));
1133 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1134 "WRONGTYPE".into(),
1135 ));
1136
1137 assert_eq!(connection.code(), 210001);
1138 assert_eq!(operation.code(), 210004);
1139 assert!(connection.source().is_some());
1140 assert!(operation.source().is_some());
1141 }
1142
1143 #[test]
1144 fn test_migration_execution_error_preserves_context_and_source() {
1145 use std::error::Error;
1146
1147 let error = BaseError::MigrationExecutionFailed {
1148 module: "accounts".into(),
1149 version: "202607150001".into(),
1150 checksum: "0123456789abcdef".into(),
1151 source: yang_db::DbError::SqlSyntaxError("bad ddl".into()),
1152 };
1153
1154 assert_eq!(error.code(), 200007);
1155 assert_eq!(error.code_str(), "200007");
1156 assert!(error.to_string().contains("accounts"));
1157 assert!(error.to_string().contains("202607150001"));
1158 assert!(error.to_string().contains("0123456789abcdef"));
1159 assert!(error.source().is_some());
1160 }
1161
1162 #[test]
1163 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1164 use std::error::Error;
1165
1166 let error = BaseError::PluginLifecycleFailed {
1167 plugin: "audit".into(),
1168 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1169 source: Box::new(std::io::Error::other("flush failed")),
1170 };
1171
1172 assert_eq!(error.code(), 100008);
1173 assert_eq!(error.code_str(), "100008");
1174 assert!(error.to_string().contains("audit"));
1175 assert!(error.to_string().contains("shutdown"));
1176 assert!(error.source().is_some());
1177 }
1178
1179 #[test]
1181 fn test_code_str_matches_code() {
1182 let samples: Vec<BaseError> = vec![
1184 BaseError::PluginNotFound("p".into()),
1185 BaseError::PluginLifecycleFailed {
1186 plugin: "p".into(),
1187 stage: crate::plugin::PluginLifecycleStage::Initialize,
1188 source: Box::new(std::io::Error::other("init")),
1189 },
1190 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1191 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1192 BaseError::MigrationExecutionFailed {
1193 module: "m".into(),
1194 version: "v1".into(),
1195 checksum: "c".into(),
1196 source: yang_db::DbError::QueryError("q".into()),
1197 },
1198 BaseError::DatabaseNotInitialized,
1199 BaseError::RedisNotInitialized,
1200 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1201 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1202 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1203 BaseError::HttpTimeout,
1204 BaseError::TokenExpired,
1205 BaseError::TokenRevoked,
1206 BaseError::JsonSerializeFailed("s".into()),
1207 BaseError::FieldNotFound("t".into(), "f".into()),
1208 BaseError::ParamInvalid("k".into(), "r".into()),
1209 BaseError::TableConfigNotSet,
1210 BaseError::ConfigError("c".into()),
1211 BaseError::Unknown("u".into()),
1212 ];
1213 for err in samples {
1214 let code = err.code();
1215 let code_str = err.code_str();
1216 assert_eq!(
1217 code_str.parse::<i32>().unwrap(),
1218 code,
1219 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1220 code_str,
1221 code,
1222 err
1223 );
1224 }
1225 }
1226
1227 #[test]
1229 fn test_error_category_coverage() {
1230 assert_eq!(
1232 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1233 ErrorCategory::Client
1234 );
1235 assert_eq!(
1236 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1237 ErrorCategory::Client
1238 );
1239 assert_eq!(
1241 BaseError::Unauthorized("u".into()).category(),
1242 ErrorCategory::Auth
1243 );
1244 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1245 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1246 assert_eq!(
1248 BaseError::RecordNotFound("r".into()).category(),
1249 ErrorCategory::NotFound
1250 );
1251 assert_eq!(
1252 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1253 ErrorCategory::NotFound
1254 );
1255 assert_eq!(
1257 BaseError::PluginAlreadyRegistered("p".into()).category(),
1258 ErrorCategory::Conflict
1259 );
1260 assert_eq!(
1262 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1263 .category(),
1264 ErrorCategory::Transient
1265 );
1266 assert_eq!(
1267 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1268 .category(),
1269 ErrorCategory::Transient
1270 );
1271 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1272 assert_eq!(
1274 BaseError::Unknown("u".into()).category(),
1275 ErrorCategory::Server
1276 );
1277 assert_eq!(
1278 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1279 ErrorCategory::Server
1280 );
1281 }
1282
1283 #[test]
1285 fn test_is_retryable() {
1286 assert!(
1287 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1288 .is_retryable()
1289 );
1290 assert!(BaseError::HttpTimeout.is_retryable());
1291 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1292 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1293 assert!(!BaseError::Unknown("u".into()).is_retryable());
1294 }
1295
1296 #[test]
1298 fn test_is_client_error() {
1299 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1300 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1301 assert!(BaseError::TokenExpired.is_client_error());
1302 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1303 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1304 assert!(
1305 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1306 .is_client_error()
1307 );
1308 assert!(!BaseError::Unknown("u".into()).is_client_error());
1309 }
1310
1311 #[test]
1313 fn test_is_server_error() {
1314 assert!(BaseError::Unknown("u".into()).is_server_error());
1315 assert!(
1316 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1317 .is_server_error()
1318 );
1319 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1320 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1321 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1322 }
1323}