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("当前后端不支持该能力: {0}")]
124 UnsupportedCapability(String),
125
126 #[error("事务与表数据源不一致 [{table}]: 期望 {expected},实际 {actual}")]
128 DatasourceMismatch {
129 table: String,
131 expected: String,
133 actual: String,
135 },
136
137 #[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
142 MissingWhereClause(String),
143
144 #[error("Redis 连接失败: {0}")]
147 RedisConnectionFailed(#[source] yang_db::DbError),
148
149 #[error("Redis 已初始化")]
151 RedisAlreadyInitialized,
152
153 #[error("Redis 未初始化")]
155 RedisNotInitialized,
156
157 #[error("Redis 操作失败: {0}")]
159 RedisOperationFailed(#[source] yang_db::DbError),
160
161 #[error("Redis 操作失败: {0}")]
163 RedisOperationDbError(#[source] yang_db::DbError),
164
165 #[cfg(feature = "http")]
168 #[error("HTTP 客户端创建失败: {0}")]
169 HttpClientCreateFailed(#[source] reqwest::Error),
170
171 #[cfg(not(feature = "http"))]
173 #[error("HTTP 客户端创建失败: {0}")]
174 HttpClientCreateFailed(String),
175
176 #[cfg(feature = "http")]
178 #[error("HTTP 请求失败: {0}")]
179 HttpRequestFailed(#[source] reqwest::Error),
180
181 #[cfg(not(feature = "http"))]
183 #[error("HTTP 请求失败: {0}")]
184 HttpRequestFailed(String),
185
186 #[error("HTTP 响应解析失败: {0}")]
188 HttpResponseParseFailed(String),
189
190 #[error("HTTP 响应体超过上限: 上限 {limit} 字节, 实际 {actual:?} 字节")]
192 HttpResponseTooLarge {
193 limit: usize,
195 actual: Option<u64>,
197 },
198
199 #[error("HTTP 请求超时")]
201 HttpTimeout,
202
203 #[error("HTTP 客户端已初始化")]
205 HttpClientAlreadyInitialized,
206
207 #[error("HTTP 客户端未初始化")]
209 HttpClientNotInitialized,
210
211 #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
213 HttpCircuitBreakerOpen(String),
214
215 #[error("上游服务暂不可用: {0}")]
226 UpstreamUnavailable(String),
227
228 #[error("Token 密钥无效: {0}")]
231 TokenKeyInvalid(String),
232
233 #[cfg(feature = "token")]
235 #[error("Token 生成失败: {0}")]
236 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
237
238 #[cfg(not(feature = "token"))]
240 #[error("Token 生成失败: {0}")]
241 TokenGenerateFailed(String),
242
243 #[cfg(feature = "token")]
245 #[error("Token 验证失败: {0}")]
246 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
247
248 #[cfg(not(feature = "token"))]
250 #[error("Token 验证失败: {0}")]
251 TokenVerifyFailed(String),
252
253 #[cfg(feature = "token")]
255 #[error("Token 解析失败: {0}")]
256 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
257
258 #[cfg(not(feature = "token"))]
260 #[error("Token 解析失败: {0}")]
261 TokenParseFailed(String),
262
263 #[error("Token 已过期")]
265 TokenExpired,
266
267 #[error("Token 已被撤销")]
269 TokenRevoked,
270
271 #[error("Token 撤销状态无效: {0}")]
273 TokenRevocationStateInvalid(String),
274
275 #[error("授权状态已变更,请刷新登录")]
277 AuthorizationStale,
278
279 #[error("授权版本无效")]
281 AuthorizationVersionInvalid,
282
283 #[error("授权状态暂时无法校验")]
285 AuthorizationCheckUnavailable,
286
287 #[error("Token 类型无效: {0}")]
289 TokenTypeInvalid(String),
290
291 #[error("JSON 序列化失败: {0}")]
294 JsonSerializeFailed(String),
295
296 #[error("JSON 反序列化失败: {0}")]
298 JsonDeserializeFailed(String),
299
300 #[error("字段类型无效 [{0}]: {1}")]
303 InvalidFieldType(String, String),
304
305 #[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
307 InvalidEnumValue(String, String),
308
309 #[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
311 StringTooLong(String, usize, usize),
312
313 #[error("JSON 格式无效 [{0}]: {1}")]
315 InvalidJsonFormat(String, String),
316
317 #[error("验证失败 [{0}]: {1}")]
319 ValidationFailed(String, String),
320
321 #[error("字段必填: {0}")]
323 FieldRequired(String),
324
325 #[error("字段未找到 [表: {0}]: {1}")]
327 FieldNotFound(String, String),
328
329 #[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
331 FieldPermissionDenied(String, String, String),
332
333 #[error("Action 未找到: {0}")]
336 ActionNotFound(String),
337
338 #[error("权限被拒绝: {0}")]
340 PermissionDenied(String),
341
342 #[error("未授权: {0}")]
344 Unauthorized(String),
345
346 #[error("参数缺失: {0}")]
348 ParamMissing(String),
349
350 #[error("参数无效 [{0}]: {1}")]
352 ParamInvalid(String, String),
353
354 #[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
356 RateLimitExceeded {
357 retry_after_seconds: u64,
359 },
360
361 #[error("需要输入双重验证码")]
366 SecondFactorRequired,
367
368 #[error("记录未找到: {0}")]
370 RecordNotFound(String),
371
372 #[error("用户未找到: {0}")]
374 UserNotFound(String),
375
376 #[error("密码无效")]
378 InvalidPassword,
379
380 #[error("表定义未设置")]
382 TableDefinitionNotSet,
383
384 #[cfg(feature = "token")]
386 #[error("敏感操作需要重新认证")]
387 StepUpRequired(crate::action::StepUpChallenge),
388
389 #[error("配置错误: {0}")]
392 ConfigError(String),
393
394 #[error("IO 错误: {0}")]
396 IoError(String),
397
398 #[error("未知错误: {0}")]
400 Unknown(String),
401}
402
403fn duplicate_key_field(message: &str) -> Option<String> {
419 if message.contains("Duplicate entry") {
420 if let Some((_, rest)) = message.split_once("for key '") {
421 let raw = rest.split('\'').next().unwrap_or_default();
423 let last = raw.rsplit('.').next().unwrap_or(raw);
424 if !last.is_empty() {
425 return Some(last.to_string());
426 }
427 }
428 }
429 if message.contains("duplicate key value violates unique constraint") {
430 if let Some((_, rest)) = message.split_once("unique constraint \"") {
431 let name = rest.split('"').next().unwrap_or_default();
432 if !name.is_empty() {
433 return Some(name.to_string());
434 }
435 }
436 }
437 None
438}
439
440#[allow(unreachable_patterns)]
455impl From<yang_db::DbError> for BaseError {
456 fn from(err: yang_db::DbError) -> Self {
457 use yang_db::DbError as D;
458 match &err {
459 D::QueryError(_)
461 | D::TableNotFound(_)
462 | D::TypeConversionError(_)
463 | D::DeserializationError(_)
464 | D::UnsupportedOperator(_)
465 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
466
467 D::DatabaseError(info) => match info.kind() {
471 yang_db::SqlErrorKind::UniqueViolation => {
472 let field = info
473 .constraint()
474 .and_then(|constraint| constraint.rsplit('.').next())
475 .map(str::to_string)
476 .or_else(|| duplicate_key_field(info.message()))
477 .unwrap_or_else(|| "unknown".to_string());
478 BaseError::ParamInvalid(field, "该值已存在".to_string())
479 }
480 yang_db::SqlErrorKind::UndefinedTable => BaseError::DatabaseQueryFailed(err),
481 yang_db::SqlErrorKind::ConnectionFailure
482 | yang_db::SqlErrorKind::TooManyConnections => {
483 BaseError::DatabaseConnectionDbError(err)
484 }
485 _ => BaseError::DatabaseExecuteFailed(err),
486 },
487
488 D::PoolClosed => BaseError::DatabaseConnectionDbError(err),
490
491 D::ConstraintError(message) => match duplicate_key_field(message) {
494 Some(field) => BaseError::ParamInvalid(field, "该值已存在".to_string()),
495 None => BaseError::DatabaseExecuteFailed(err),
496 },
497
498 D::SqlSyntaxError(_)
500 | D::MissingWhereClause
501 | D::MissingGroupByClause
502 | D::InvalidArgument(_)
503 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
504
505 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
507
508 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
510
511 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
513
514 D::RedisCommandError(_)
516 | D::RedisPoolError(_)
517 | D::RedisPoolClosed
518 | D::RedisError(_)
519 | D::RedisTypeConversionError(_)
520 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
521
522 _ => BaseError::DatabaseQueryFailed(err),
524 }
525 }
526}
527
528impl From<std::io::Error> for BaseError {
530 fn from(err: std::io::Error) -> Self {
531 BaseError::IoError(err.to_string())
532 }
533}
534
535impl From<serde_json::Error> for BaseError {
537 fn from(err: serde_json::Error) -> Self {
538 if err.is_syntax() || err.is_data() || err.is_eof() {
539 BaseError::JsonDeserializeFailed(err.to_string())
540 } else {
541 BaseError::JsonSerializeFailed(err.to_string())
542 }
543 }
544}
545
546#[cfg(feature = "http")]
548impl From<reqwest::Error> for BaseError {
549 fn from(err: reqwest::Error) -> Self {
550 if err.is_timeout() {
551 BaseError::HttpTimeout
552 } else {
553 BaseError::HttpRequestFailed(err)
557 }
558 }
559}
560
561#[cfg(feature = "token")]
568impl From<jsonwebtoken::errors::Error> for BaseError {
569 fn from(err: jsonwebtoken::errors::Error) -> Self {
570 use jsonwebtoken::errors::ErrorKind;
571 match err.kind() {
572 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
573 ErrorKind::InvalidToken
574 | ErrorKind::InvalidSignature
575 | ErrorKind::InvalidIssuer
576 | ErrorKind::InvalidAudience
577 | ErrorKind::InvalidSubject
578 | ErrorKind::InvalidAlgorithm
579 | ErrorKind::MissingAlgorithm
580 | ErrorKind::ImmatureSignature
581 | ErrorKind::MissingRequiredClaim(_)
582 | ErrorKind::InvalidEcdsaKey
583 | ErrorKind::InvalidRsaKey(_)
584 | ErrorKind::InvalidKeyFormat
585 | ErrorKind::RsaFailedSigning
586 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
587 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
589 BaseError::TokenParseFailed(err)
590 }
591 _ => BaseError::TokenVerifyFailed(err),
593 }
594 }
595}
596
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605#[non_exhaustive]
606pub enum ErrorCategory {
607 Client,
609 Auth,
611 NotFound,
613 Conflict,
615 Transient,
620 Server,
622}
623
624pub const NOT_READY_CODE: i32 = 900001;
629
630impl BaseError {
631 pub fn code(&self) -> i32 {
660 match self {
661 BaseError::PluginAlreadyRegistered(_) => 100001,
663 BaseError::PluginNotFound(_) => 100002,
664 BaseError::PluginRegisterFailed(_, _) => 100003,
665 BaseError::PluginInitFailed(_, _) => 100004,
666 BaseError::PluginDependencyMissing(_, _) => 100005,
667 BaseError::PluginCircularDependency(_) => 100006,
668 BaseError::PluginConfigInvalid(_, _) => 100007,
669 BaseError::PluginShutdownFailed(_, _) => 100008,
670 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
671 crate::plugin::PluginLifecycleStage::Register => 100003,
672 crate::plugin::PluginLifecycleStage::Initialize => 100004,
673 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
674 },
675
676 BaseError::DatabaseConnectionFailed(_) => 200001,
678 BaseError::DatabaseConnectionDbError(_) => 200011,
679 BaseError::DatabaseAlreadyInitialized => 200002,
680 BaseError::DatabaseQueryFailed(_) => 200003,
681 BaseError::DatabaseExecuteFailed(_) => 200004,
682 BaseError::DatabaseInitFailed(_) => 200005,
683 BaseError::DatabaseNotInitialized => 200008,
684 BaseError::DatabaseTransactionFailed(_) => 200009,
685 BaseError::MissingWhereClause(_) => 200010,
686 BaseError::UnsupportedCapability(_) => 200012,
687 BaseError::DatasourceMismatch { .. } => 200013,
688
689 BaseError::RedisConnectionFailed(_) => 210001,
691 BaseError::RedisAlreadyInitialized => 210002,
692 BaseError::RedisNotInitialized => 210003,
693 BaseError::RedisOperationFailed(_) => 210004,
694 BaseError::RedisOperationDbError(_) => 210011,
695
696 BaseError::HttpClientCreateFailed(_) => 300001,
698 BaseError::HttpRequestFailed(_) => 300002,
699 BaseError::HttpResponseParseFailed(_) => 300003,
700 BaseError::HttpTimeout => 300004,
701 BaseError::HttpClientAlreadyInitialized => 300005,
702 BaseError::HttpClientNotInitialized => 300006,
703 BaseError::HttpCircuitBreakerOpen(_) => 300007,
704 BaseError::HttpResponseTooLarge { .. } => 300008,
705 BaseError::UpstreamUnavailable(_) => 300009,
708
709 BaseError::TokenKeyInvalid(_) => 400001,
711 BaseError::TokenGenerateFailed(_) => 400002,
712 BaseError::TokenVerifyFailed(_) => 400003,
713 BaseError::TokenParseFailed(_) => 400004,
714 BaseError::TokenExpired => 400005,
715 BaseError::TokenTypeInvalid(_) => 400006,
716 BaseError::TokenRevoked => 400007,
717 BaseError::TokenRevocationStateInvalid(_) => 400008,
718 BaseError::AuthorizationStale => 400009,
719 BaseError::AuthorizationVersionInvalid => 400010,
720 BaseError::AuthorizationCheckUnavailable => 400011,
721
722 BaseError::JsonSerializeFailed(_) => 500001,
724 BaseError::JsonDeserializeFailed(_) => 500002,
725
726 BaseError::InvalidFieldType(_, _) => 600001,
728 BaseError::InvalidEnumValue(_, _) => 600002,
729 BaseError::StringTooLong(_, _, _) => 600003,
730 BaseError::InvalidJsonFormat(_, _) => 600004,
731 BaseError::ValidationFailed(_, _) => 600005,
732 BaseError::FieldRequired(_) => 600006,
733 BaseError::FieldNotFound(_, _) => 600007,
734 BaseError::FieldPermissionDenied(_, _, _) => 600008,
735
736 BaseError::ActionNotFound(_) => 700001,
738 BaseError::PermissionDenied(_) => 700002,
739 BaseError::Unauthorized(_) => 700003,
740 BaseError::ParamMissing(_) => 700004,
741 BaseError::ParamInvalid(_, _) => 700005,
742 BaseError::RecordNotFound(_) => 700006,
743 BaseError::UserNotFound(_) => 700007,
744 BaseError::InvalidPassword => 700008,
745 BaseError::TableDefinitionNotSet => 700009,
746 #[cfg(feature = "token")]
747 BaseError::StepUpRequired(_) => 700010,
748 BaseError::RateLimitExceeded { .. } => 700011,
749 BaseError::SecondFactorRequired => 700012,
750
751 BaseError::ConfigError(_) => 900001,
753 BaseError::IoError(_) => 900002,
754 BaseError::Unknown(_) => 999999,
755 }
756 }
757
758 pub fn code_str(&self) -> &'static str {
765 match self {
766 BaseError::PluginAlreadyRegistered(_) => "100001",
768 BaseError::PluginNotFound(_) => "100002",
769 BaseError::PluginRegisterFailed(_, _) => "100003",
770 BaseError::PluginInitFailed(_, _) => "100004",
771 BaseError::PluginDependencyMissing(_, _) => "100005",
772 BaseError::PluginCircularDependency(_) => "100006",
773 BaseError::PluginConfigInvalid(_, _) => "100007",
774 BaseError::PluginShutdownFailed(_, _) => "100008",
775 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
776 crate::plugin::PluginLifecycleStage::Register => "100003",
777 crate::plugin::PluginLifecycleStage::Initialize => "100004",
778 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
779 },
780 BaseError::DatabaseConnectionFailed(_) => "200001",
782 BaseError::DatabaseConnectionDbError(_) => "200011",
783 BaseError::DatabaseAlreadyInitialized => "200002",
784 BaseError::DatabaseQueryFailed(_) => "200003",
785 BaseError::DatabaseExecuteFailed(_) => "200004",
786 BaseError::DatabaseInitFailed(_) => "200005",
787 BaseError::DatabaseNotInitialized => "200008",
788 BaseError::DatabaseTransactionFailed(_) => "200009",
789 BaseError::MissingWhereClause(_) => "200010",
790 BaseError::UnsupportedCapability(_) => "200012",
791 BaseError::DatasourceMismatch { .. } => "200013",
792 BaseError::RedisConnectionFailed(_) => "210001",
794 BaseError::RedisAlreadyInitialized => "210002",
795 BaseError::RedisNotInitialized => "210003",
796 BaseError::RedisOperationFailed(_) => "210004",
797 BaseError::RedisOperationDbError(_) => "210011",
798 BaseError::HttpClientCreateFailed(_) => "300001",
800 BaseError::HttpRequestFailed(_) => "300002",
801 BaseError::HttpResponseParseFailed(_) => "300003",
802 BaseError::HttpTimeout => "300004",
803 BaseError::HttpClientAlreadyInitialized => "300005",
804 BaseError::HttpClientNotInitialized => "300006",
805 BaseError::HttpCircuitBreakerOpen(_) => "300007",
806 BaseError::HttpResponseTooLarge { .. } => "300008",
807 BaseError::UpstreamUnavailable(_) => "300009",
808 BaseError::TokenKeyInvalid(_) => "400001",
810 BaseError::TokenGenerateFailed(_) => "400002",
811 BaseError::TokenVerifyFailed(_) => "400003",
812 BaseError::TokenParseFailed(_) => "400004",
813 BaseError::TokenExpired => "400005",
814 BaseError::TokenTypeInvalid(_) => "400006",
815 BaseError::TokenRevoked => "400007",
816 BaseError::TokenRevocationStateInvalid(_) => "400008",
817 BaseError::AuthorizationStale => "400009",
818 BaseError::AuthorizationVersionInvalid => "400010",
819 BaseError::AuthorizationCheckUnavailable => "400011",
820 BaseError::JsonSerializeFailed(_) => "500001",
822 BaseError::JsonDeserializeFailed(_) => "500002",
823 BaseError::InvalidFieldType(_, _) => "600001",
825 BaseError::InvalidEnumValue(_, _) => "600002",
826 BaseError::StringTooLong(_, _, _) => "600003",
827 BaseError::InvalidJsonFormat(_, _) => "600004",
828 BaseError::ValidationFailed(_, _) => "600005",
829 BaseError::FieldRequired(_) => "600006",
830 BaseError::FieldNotFound(_, _) => "600007",
831 BaseError::FieldPermissionDenied(_, _, _) => "600008",
832 BaseError::ActionNotFound(_) => "700001",
834 BaseError::PermissionDenied(_) => "700002",
835 BaseError::Unauthorized(_) => "700003",
836 BaseError::ParamMissing(_) => "700004",
837 BaseError::ParamInvalid(_, _) => "700005",
838 BaseError::RecordNotFound(_) => "700006",
839 BaseError::UserNotFound(_) => "700007",
840 BaseError::InvalidPassword => "700008",
841 BaseError::TableDefinitionNotSet => "700009",
842 #[cfg(feature = "token")]
843 BaseError::StepUpRequired(_) => "700010",
844 BaseError::RateLimitExceeded { .. } => "700011",
845 BaseError::SecondFactorRequired => "700012",
846 BaseError::ConfigError(_) => "900001",
848 BaseError::IoError(_) => "900002",
849 BaseError::Unknown(_) => "999999",
850 }
851 }
852
853 pub fn category(&self) -> ErrorCategory {
863 use ErrorCategory as C;
864 match self {
865 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
867 BaseError::PluginCircularDependency(_) => C::Client,
868 BaseError::PluginDependencyMissing(_, _) => C::Client,
869 BaseError::PluginConfigInvalid(_, _) => C::Client,
870 BaseError::PluginNotFound(_)
871 | BaseError::PluginRegisterFailed(_, _)
872 | BaseError::PluginInitFailed(_, _)
873 | BaseError::PluginShutdownFailed(_, _)
874 | BaseError::PluginLifecycleFailed { .. } => C::Server,
875 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
878 C::Transient
879 }
880 BaseError::MissingWhereClause(_) => C::Client,
881 BaseError::UnsupportedCapability(_) => C::Server,
882 BaseError::DatabaseAlreadyInitialized
883 | BaseError::DatabaseNotInitialized
884 | BaseError::DatabaseInitFailed(_)
885 | BaseError::DatasourceMismatch { .. } => C::Server,
886 BaseError::DatabaseQueryFailed(_)
888 | BaseError::DatabaseExecuteFailed(_)
889 | BaseError::DatabaseTransactionFailed(_) => C::Server,
890 BaseError::RedisConnectionFailed(_) => C::Transient,
892 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
893 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
894 match source.category() {
895 yang_db::DbErrorCategory::Transient => C::Transient,
896 yang_db::DbErrorCategory::Conflict => C::Conflict,
897 yang_db::DbErrorCategory::Client => C::Client,
898 yang_db::DbErrorCategory::NotFound => C::NotFound,
899 yang_db::DbErrorCategory::Server => C::Server,
900 _ => C::Server,
901 }
902 }
903 BaseError::HttpClientCreateFailed(_)
905 | BaseError::HttpClientNotInitialized
906 | BaseError::HttpClientAlreadyInitialized => C::Client,
907 BaseError::HttpResponseParseFailed(_) => C::Client,
909 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
910 BaseError::UpstreamUnavailable(_) => C::Transient,
912 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
914 BaseError::HttpResponseTooLarge { .. } => C::Server,
916 BaseError::TokenKeyInvalid(_)
918 | BaseError::TokenGenerateFailed(_)
919 | BaseError::TokenTypeInvalid(_)
920 | BaseError::TokenParseFailed(_) => C::Client,
921 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
922 C::Auth
923 }
924 BaseError::TokenRevocationStateInvalid(_) => C::Server,
925 BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
926 BaseError::AuthorizationCheckUnavailable => C::Transient,
927 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
929 BaseError::InvalidFieldType(_, _)
931 | BaseError::InvalidEnumValue(_, _)
932 | BaseError::StringTooLong(_, _, _)
933 | BaseError::InvalidJsonFormat(_, _)
934 | BaseError::ValidationFailed(_, _)
935 | BaseError::FieldRequired(_)
936 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
937 BaseError::FieldNotFound(_, _) => C::NotFound,
938 BaseError::Unauthorized(_)
940 | BaseError::PermissionDenied(_)
941 | BaseError::SecondFactorRequired => C::Auth,
942 BaseError::ParamMissing(_)
943 | BaseError::ParamInvalid(_, _)
944 | BaseError::RateLimitExceeded { .. } => C::Client,
945 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
946 BaseError::InvalidPassword => C::Auth,
947 BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
948 #[cfg(feature = "token")]
949 BaseError::StepUpRequired(_) => C::Client,
950 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
952 }
953 }
954
955 fn db_error(&self) -> Option<&yang_db::DbError> {
957 match self {
958 BaseError::DatabaseConnectionFailed(err)
959 | BaseError::DatabaseConnectionDbError(err)
960 | BaseError::DatabaseQueryFailed(err)
961 | BaseError::DatabaseExecuteFailed(err)
962 | BaseError::DatabaseTransactionFailed(err)
963 | BaseError::RedisConnectionFailed(err)
964 | BaseError::RedisOperationFailed(err)
965 | BaseError::RedisOperationDbError(err) => Some(err),
966 _ => None,
967 }
968 }
969
970 pub fn sql_error_info(&self) -> Option<&yang_db::SqlErrorInfo> {
975 match self.db_error()? {
976 yang_db::DbError::DatabaseError(info) => Some(info.as_ref()),
977 _ => None,
978 }
979 }
980
981 pub fn sqlstate(&self) -> Option<&str> {
983 self.sql_error_info().map(yang_db::SqlErrorInfo::code)
984 }
985
986 pub fn constraint(&self) -> Option<&str> {
988 self.sql_error_info()
989 .and_then(yang_db::SqlErrorInfo::constraint)
990 }
991
992 pub fn is_retryable(&self) -> bool {
998 self.db_error().map_or_else(
999 || self.category() == ErrorCategory::Transient,
1000 |err| err.is_retryable(),
1001 )
1002 }
1003
1004 pub fn is_transaction_aborted(&self) -> bool {
1008 self.sql_error_info()
1009 .is_some_and(|info| info.kind() == yang_db::SqlErrorKind::InFailedTransaction)
1010 }
1011
1012 pub fn is_timeout(&self) -> bool {
1015 matches!(self, BaseError::HttpTimeout)
1016 || self.sql_error_info().is_some_and(|info| {
1017 matches!(
1018 info.kind(),
1019 yang_db::SqlErrorKind::QueryCanceled | yang_db::SqlErrorKind::LockNotAvailable
1020 )
1021 })
1022 }
1023
1024 pub fn is_client_error(&self) -> bool {
1030 matches!(
1031 self.category(),
1032 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
1033 )
1034 }
1035
1036 pub fn is_server_error(&self) -> bool {
1042 matches!(
1043 self.category(),
1044 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
1045 )
1046 }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051 use super::*;
1052
1053 #[test]
1054 fn test_not_ready_code_is_stable() {
1055 assert_eq!(NOT_READY_CODE, 900001);
1056 }
1057
1058 #[test]
1059 fn test_error_codes_plugin() {
1060 assert_eq!(
1061 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
1062 100001
1063 );
1064 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
1065 assert_eq!(
1066 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
1067 100003
1068 );
1069 assert_eq!(
1070 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
1071 100004
1072 );
1073 assert_eq!(
1074 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
1075 100005
1076 );
1077 assert_eq!(
1078 BaseError::PluginCircularDependency("test".to_string()).code(),
1079 100006
1080 );
1081 assert_eq!(
1082 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
1083 100007
1084 );
1085 assert_eq!(
1086 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
1087 100008
1088 );
1089 }
1090
1091 #[test]
1092 fn test_error_codes_database() {
1093 assert_eq!(
1094 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
1095 "reason".to_string()
1096 ))
1097 .code(),
1098 200001
1099 );
1100 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
1101 assert_eq!(
1102 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
1103 .code(),
1104 200003
1105 );
1106 assert_eq!(
1107 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
1108 .code(),
1109 200004
1110 );
1111 assert_eq!(
1112 BaseError::DatabaseInitFailed("reason".to_string()).code(),
1113 200005
1114 );
1115 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
1116 assert_eq!(
1117 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
1118 "reason".to_string()
1119 ))
1120 .code(),
1121 200009
1122 );
1123 }
1124
1125 #[cfg(feature = "http")]
1126 #[test]
1127 fn test_error_codes_http() {
1128 assert_eq!(
1130 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
1131 300003
1132 );
1133 assert_eq!(BaseError::HttpTimeout.code(), 300004);
1134 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
1135 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
1136 }
1137
1138 #[cfg(feature = "token")]
1139 #[test]
1140 fn test_error_codes_token() {
1141 assert_eq!(
1142 BaseError::TokenKeyInvalid("reason".to_string()).code(),
1143 400001
1144 );
1145 assert_eq!(
1146 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
1147 jsonwebtoken::errors::ErrorKind::InvalidToken
1148 ))
1149 .code(),
1150 400002
1151 );
1152 assert_eq!(
1153 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
1154 jsonwebtoken::errors::ErrorKind::InvalidToken
1155 ))
1156 .code(),
1157 400003
1158 );
1159 assert_eq!(
1160 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
1161 jsonwebtoken::errors::ErrorKind::InvalidToken
1162 ))
1163 .code(),
1164 400004
1165 );
1166 assert_eq!(BaseError::TokenExpired.code(), 400005);
1167 assert_eq!(
1168 BaseError::TokenTypeInvalid("reason".to_string()).code(),
1169 400006
1170 );
1171 }
1172
1173 #[test]
1174 fn test_error_codes_serialization() {
1175 assert_eq!(
1176 BaseError::JsonSerializeFailed("reason".to_string()).code(),
1177 500001
1178 );
1179 assert_eq!(
1180 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
1181 500002
1182 );
1183 }
1184
1185 #[test]
1186 fn test_error_codes_field_validation() {
1187 assert_eq!(
1188 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
1189 600001
1190 );
1191 assert_eq!(
1192 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1193 600002
1194 );
1195 assert_eq!(
1196 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1197 600003
1198 );
1199 assert_eq!(
1200 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1201 600004
1202 );
1203 assert_eq!(
1204 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1205 600005
1206 );
1207 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1208 assert_eq!(
1209 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1210 600007
1211 );
1212 assert_eq!(
1213 BaseError::FieldPermissionDenied(
1214 "table".to_string(),
1215 "field".to_string(),
1216 "reason".to_string()
1217 )
1218 .code(),
1219 600008
1220 );
1221 }
1222
1223 #[test]
1224 fn test_error_codes_action_system() {
1225 assert_eq!(
1226 BaseError::ActionNotFound("test_action".to_string()).code(),
1227 700001
1228 );
1229 assert_eq!(
1230 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1231 700002
1232 );
1233 assert_eq!(
1234 BaseError::Unauthorized("Token 无效".to_string()).code(),
1235 700003
1236 );
1237 assert_eq!(
1238 BaseError::ParamMissing("user_id".to_string()).code(),
1239 700004
1240 );
1241 assert_eq!(
1242 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1243 700005
1244 );
1245 assert_eq!(
1246 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1247 700006
1248 );
1249 assert_eq!(
1250 BaseError::UserNotFound("user_123".to_string()).code(),
1251 700007
1252 );
1253 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1254 assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1255 assert_eq!(
1256 BaseError::RateLimitExceeded {
1257 retry_after_seconds: 30
1258 }
1259 .code(),
1260 700011
1261 );
1262 assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
1263 assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
1264 }
1265
1266 #[test]
1267 fn test_error_codes_general() {
1268 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1269 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1270 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1271 }
1272
1273 #[test]
1274 fn test_all_error_codes_are_nonzero() {
1275 let errors: Vec<BaseError> = vec![
1277 BaseError::PluginNotFound("test".to_string()),
1278 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1279 BaseError::HttpTimeout,
1280 BaseError::TokenExpired,
1281 BaseError::JsonSerializeFailed("test".to_string()),
1282 BaseError::FieldRequired("test".to_string()),
1283 BaseError::ActionNotFound("test".to_string()),
1284 BaseError::PermissionDenied("test".to_string()),
1285 BaseError::Unauthorized("test".to_string()),
1286 BaseError::ParamMissing("test".to_string()),
1287 BaseError::RecordNotFound("test".to_string()),
1288 BaseError::UserNotFound("test".to_string()),
1289 BaseError::InvalidPassword,
1290 BaseError::TableDefinitionNotSet,
1291 BaseError::RateLimitExceeded {
1292 retry_after_seconds: 30,
1293 },
1294 BaseError::Unknown("test".to_string()),
1295 ];
1296
1297 for error in errors {
1298 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1299 }
1300 }
1301
1302 #[test]
1304 fn test_database_error_source_chain() {
1305 use std::error::Error;
1306
1307 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1308 let base_err = BaseError::DatabaseQueryFailed(db_err);
1309
1310 let source = base_err.source();
1312 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1313 }
1314
1315 #[test]
1317 fn test_from_db_error_preserves_source() {
1318 use std::error::Error;
1319
1320 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1321 let base_err: BaseError = db_err.into();
1322
1323 assert!(base_err.source().is_some());
1325 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1326 }
1327
1328 #[test]
1329 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1330 use std::error::Error;
1331
1332 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1333 "connection refused".into(),
1334 ));
1335 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1336 "WRONGTYPE".into(),
1337 ));
1338
1339 assert_eq!(connection.code(), 210001);
1340 assert_eq!(operation.code(), 210004);
1341 assert!(connection.source().is_some());
1342 assert!(operation.source().is_some());
1343 }
1344
1345 #[test]
1346 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1347 use std::error::Error;
1348
1349 let error = BaseError::PluginLifecycleFailed {
1350 plugin: "audit".into(),
1351 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1352 source: Box::new(std::io::Error::other("flush failed")),
1353 };
1354
1355 assert_eq!(error.code(), 100008);
1356 assert_eq!(error.code_str(), "100008");
1357 assert!(error.to_string().contains("audit"));
1358 assert!(error.to_string().contains("shutdown"));
1359 assert!(error.source().is_some());
1360 }
1361
1362 #[test]
1364 fn test_code_str_matches_code() {
1365 let samples: Vec<BaseError> = vec![
1367 BaseError::PluginNotFound("p".into()),
1368 BaseError::PluginLifecycleFailed {
1369 plugin: "p".into(),
1370 stage: crate::plugin::PluginLifecycleStage::Initialize,
1371 source: Box::new(std::io::Error::other("init")),
1372 },
1373 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1374 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1375 BaseError::DatabaseNotInitialized,
1376 BaseError::RedisNotInitialized,
1377 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1378 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1379 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1380 BaseError::HttpTimeout,
1381 BaseError::TokenExpired,
1382 BaseError::TokenRevoked,
1383 BaseError::TokenRevocationStateInvalid("invalid".into()),
1384 BaseError::AuthorizationStale,
1385 BaseError::AuthorizationVersionInvalid,
1386 BaseError::AuthorizationCheckUnavailable,
1387 BaseError::JsonSerializeFailed("s".into()),
1388 BaseError::FieldNotFound("t".into(), "f".into()),
1389 BaseError::ParamInvalid("k".into(), "r".into()),
1390 BaseError::TableDefinitionNotSet,
1391 BaseError::RateLimitExceeded {
1392 retry_after_seconds: 30,
1393 },
1394 BaseError::SecondFactorRequired,
1395 BaseError::ConfigError("c".into()),
1396 BaseError::Unknown("u".into()),
1397 ];
1398 for err in samples {
1399 let code = err.code();
1400 let code_str = err.code_str();
1401 assert_eq!(
1402 code_str.parse::<i32>().unwrap(),
1403 code,
1404 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1405 code_str,
1406 code,
1407 err
1408 );
1409 }
1410 }
1411
1412 #[test]
1414 fn test_error_category_coverage() {
1415 assert_eq!(
1417 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1418 ErrorCategory::Client
1419 );
1420 assert_eq!(
1421 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1422 ErrorCategory::Client
1423 );
1424 assert_eq!(
1426 BaseError::Unauthorized("u".into()).category(),
1427 ErrorCategory::Auth
1428 );
1429 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1430 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1431 assert_eq!(
1432 BaseError::SecondFactorRequired.category(),
1433 ErrorCategory::Auth
1434 );
1435 assert_eq!(
1437 BaseError::RecordNotFound("r".into()).category(),
1438 ErrorCategory::NotFound
1439 );
1440 assert_eq!(
1441 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1442 ErrorCategory::NotFound
1443 );
1444 assert_eq!(
1446 BaseError::PluginAlreadyRegistered("p".into()).category(),
1447 ErrorCategory::Conflict
1448 );
1449 assert_eq!(
1451 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1452 .category(),
1453 ErrorCategory::Transient
1454 );
1455 assert_eq!(
1456 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1457 .category(),
1458 ErrorCategory::Transient
1459 );
1460 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1461 assert_eq!(
1463 BaseError::Unknown("u".into()).category(),
1464 ErrorCategory::Server
1465 );
1466 assert_eq!(
1467 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1468 ErrorCategory::Server
1469 );
1470 }
1471
1472 #[test]
1474 fn test_is_retryable() {
1475 assert!(
1476 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1477 .is_retryable()
1478 );
1479 assert!(BaseError::HttpTimeout.is_retryable());
1480 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1481 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1482 assert!(!BaseError::Unknown("u".into()).is_retryable());
1483 }
1484
1485 #[test]
1487 fn test_is_client_error() {
1488 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1489 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1490 assert!(BaseError::TokenExpired.is_client_error());
1491 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1492 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1493 assert!(
1494 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1495 .is_client_error()
1496 );
1497 assert!(!BaseError::Unknown("u".into()).is_client_error());
1498 }
1499
1500 #[test]
1502 fn test_is_server_error() {
1503 assert!(BaseError::Unknown("u".into()).is_server_error());
1504 assert!(
1505 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1506 .is_server_error()
1507 );
1508 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1509 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1510 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1511 }
1512
1513 #[test]
1515 fn mysql_duplicate_entry_maps_to_param_invalid_naming_the_key() {
1516 let error = BaseError::from(yang_db::DbError::ConstraintError(
1520 "Duplicate entry 'payment_currency' for key 'source_key'".to_string(),
1521 ));
1522 match error {
1523 BaseError::ParamInvalid(field, message) => {
1524 assert_eq!(field, "source_key", "要点名冲突的键");
1525 assert!(!message.is_empty());
1526 }
1527 other => panic!("唯一键冲突应映射为 ParamInvalid,实际: {other:?}"),
1528 }
1529 }
1530
1531 #[test]
1533 fn qualified_mysql_key_name_keeps_only_the_last_segment() {
1534 assert_eq!(
1535 duplicate_key_field(
1536 "Duplicate entry 'x' for key 'yang_system.feishu_datasource.source_key'"
1537 ),
1538 Some("source_key".to_string())
1539 );
1540 }
1541
1542 #[test]
1544 fn postgres_unique_violation_maps_to_param_invalid() {
1545 let error = BaseError::from(yang_db::DbError::ConstraintError(
1546 "duplicate key value violates unique constraint \"feishu_option_option_id_key\""
1547 .to_string(),
1548 ));
1549 match error {
1550 BaseError::ParamInvalid(field, _) => assert_eq!(field, "feishu_option_option_id_key"),
1551 other => panic!("PG 唯一约束冲突应映射为 ParamInvalid,实际: {other:?}"),
1552 }
1553 }
1554
1555 #[test]
1560 fn other_constraint_errors_keep_their_own_mapping() {
1561 for message in [
1562 "Cannot add or update a child row: a foreign key constraint fails",
1563 "Column 'title' cannot be null",
1564 "Check constraint 'positive_amount' is violated",
1565 ] {
1566 let error = BaseError::from(yang_db::DbError::ConstraintError(message.to_string()));
1567 assert!(
1568 !matches!(error, BaseError::ParamInvalid(_, _)),
1569 "{message:?} 不该被当成参数非法,实际: {error:?}"
1570 );
1571 }
1572 }
1573
1574 #[test]
1576 fn duplicate_key_field_returns_none_for_unrecognised_messages() {
1577 assert_eq!(duplicate_key_field(""), None);
1578 assert_eq!(
1579 duplicate_key_field("Duplicate entry 'x'"),
1580 None,
1581 "缺 for key 段就该放弃提取,而不是编一个名字出来"
1582 );
1583 assert_eq!(duplicate_key_field("some other db error"), None);
1584 }
1585
1586 fn sql_error(code: &str, constraint: Option<&str>) -> BaseError {
1587 let mut info = yang_db::SqlErrorInfo::new(code, format!("sqlstate {code}"));
1588 if let Some(constraint) = constraint {
1589 info = info.with_constraint(Some(constraint.to_string()));
1590 }
1591 BaseError::DatabaseExecuteFailed(yang_db::DbError::DatabaseError(Box::new(info)))
1592 }
1593
1594 #[test]
1597 fn sqlstate_semantics_are_exposed_from_wrapped_db_error() {
1598 for code in ["40001", "40P01"] {
1600 let error = sql_error(code, None);
1601 assert!(error.is_retryable(), "{code} 应可重试");
1602 assert!(!error.is_timeout(), "{code} 不是超时");
1603 assert!(!error.is_transaction_aborted(), "{code} 不是事务中止");
1604 }
1605
1606 assert!(sql_error("08006", None).is_retryable());
1608 assert!(sql_error("53300", None).is_retryable());
1609
1610 for code in ["55P03", "57014"] {
1612 let error = sql_error(code, None);
1613 assert!(!error.is_retryable(), "{code} 不应自动重试");
1614 assert!(error.is_timeout(), "{code} 应识别为超时/取消");
1615 }
1616
1617 let aborted = sql_error("25P02", None);
1619 assert!(aborted.is_transaction_aborted());
1620 assert!(!aborted.is_retryable());
1621 assert!(!aborted.is_timeout());
1622 assert!(!sql_error("40001", None).is_transaction_aborted());
1623 }
1624
1625 #[test]
1627 fn constraint_errors_keep_sqlstate_and_constraint_context() {
1628 let foreign_key = sql_error("23503", Some("orders_user_id_fkey"));
1629 assert_eq!(foreign_key.sqlstate(), Some("23503"));
1630 assert_eq!(foreign_key.constraint(), Some("orders_user_id_fkey"));
1631 assert!(!foreign_key.is_retryable());
1632 assert!(foreign_key.is_server_error());
1633
1634 let not_null = sql_error("23502", Some("users_email_not_null"));
1635 assert_eq!(not_null.sqlstate(), Some("23502"));
1636 assert_eq!(not_null.constraint(), Some("users_email_not_null"));
1637
1638 let check = sql_error("23514", Some("positive_amount"));
1639 assert_eq!(check.constraint(), Some("positive_amount"));
1640
1641 let plain = BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("boom".into()));
1643 assert_eq!(plain.sqlstate(), None);
1644 assert_eq!(plain.constraint(), None);
1645 }
1646}