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("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
131 MissingWhereClause(String),
132
133 #[error("Redis 连接失败: {0}")]
136 RedisConnectionFailed(#[source] yang_db::DbError),
137
138 #[error("Redis 已初始化")]
140 RedisAlreadyInitialized,
141
142 #[error("Redis 未初始化")]
144 RedisNotInitialized,
145
146 #[error("Redis 操作失败: {0}")]
148 RedisOperationFailed(#[source] yang_db::DbError),
149
150 #[error("Redis 操作失败: {0}")]
152 RedisOperationDbError(#[source] yang_db::DbError),
153
154 #[cfg(feature = "http")]
157 #[error("HTTP 客户端创建失败: {0}")]
158 HttpClientCreateFailed(#[source] reqwest::Error),
159
160 #[cfg(not(feature = "http"))]
162 #[error("HTTP 客户端创建失败: {0}")]
163 HttpClientCreateFailed(String),
164
165 #[cfg(feature = "http")]
167 #[error("HTTP 请求失败: {0}")]
168 HttpRequestFailed(#[source] reqwest::Error),
169
170 #[cfg(not(feature = "http"))]
172 #[error("HTTP 请求失败: {0}")]
173 HttpRequestFailed(String),
174
175 #[error("HTTP 响应解析失败: {0}")]
177 HttpResponseParseFailed(String),
178
179 #[error("HTTP 响应体超过上限: 上限 {limit} 字节, 实际 {actual:?} 字节")]
181 HttpResponseTooLarge {
182 limit: usize,
184 actual: Option<u64>,
186 },
187
188 #[error("HTTP 请求超时")]
190 HttpTimeout,
191
192 #[error("HTTP 客户端已初始化")]
194 HttpClientAlreadyInitialized,
195
196 #[error("HTTP 客户端未初始化")]
198 HttpClientNotInitialized,
199
200 #[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
202 HttpCircuitBreakerOpen(String),
203
204 #[error("上游服务暂不可用: {0}")]
215 UpstreamUnavailable(String),
216
217 #[error("Token 密钥无效: {0}")]
220 TokenKeyInvalid(String),
221
222 #[cfg(feature = "token")]
224 #[error("Token 生成失败: {0}")]
225 TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
226
227 #[cfg(not(feature = "token"))]
229 #[error("Token 生成失败: {0}")]
230 TokenGenerateFailed(String),
231
232 #[cfg(feature = "token")]
234 #[error("Token 验证失败: {0}")]
235 TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
236
237 #[cfg(not(feature = "token"))]
239 #[error("Token 验证失败: {0}")]
240 TokenVerifyFailed(String),
241
242 #[cfg(feature = "token")]
244 #[error("Token 解析失败: {0}")]
245 TokenParseFailed(#[source] jsonwebtoken::errors::Error),
246
247 #[cfg(not(feature = "token"))]
249 #[error("Token 解析失败: {0}")]
250 TokenParseFailed(String),
251
252 #[error("Token 已过期")]
254 TokenExpired,
255
256 #[error("Token 已被撤销")]
258 TokenRevoked,
259
260 #[error("Token 撤销状态无效: {0}")]
262 TokenRevocationStateInvalid(String),
263
264 #[error("授权状态已变更,请刷新登录")]
266 AuthorizationStale,
267
268 #[error("授权版本无效")]
270 AuthorizationVersionInvalid,
271
272 #[error("授权状态暂时无法校验")]
274 AuthorizationCheckUnavailable,
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("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
345 RateLimitExceeded {
346 retry_after_seconds: u64,
348 },
349
350 #[error("需要输入双重验证码")]
355 SecondFactorRequired,
356
357 #[error("记录未找到: {0}")]
359 RecordNotFound(String),
360
361 #[error("用户未找到: {0}")]
363 UserNotFound(String),
364
365 #[error("密码无效")]
367 InvalidPassword,
368
369 #[error("表定义未设置")]
371 TableDefinitionNotSet,
372
373 #[cfg(feature = "token")]
375 #[error("敏感操作需要重新认证")]
376 StepUpRequired(crate::action::StepUpChallenge),
377
378 #[error("配置错误: {0}")]
381 ConfigError(String),
382
383 #[error("IO 错误: {0}")]
385 IoError(String),
386
387 #[error("未知错误: {0}")]
389 Unknown(String),
390}
391
392fn duplicate_key_field(message: &str) -> Option<String> {
408 if message.contains("Duplicate entry") {
409 if let Some((_, rest)) = message.split_once("for key '") {
410 let raw = rest.split('\'').next().unwrap_or_default();
412 let last = raw.rsplit('.').next().unwrap_or(raw);
413 if !last.is_empty() {
414 return Some(last.to_string());
415 }
416 }
417 }
418 if message.contains("duplicate key value violates unique constraint") {
419 if let Some((_, rest)) = message.split_once("unique constraint \"") {
420 let name = rest.split('"').next().unwrap_or_default();
421 if !name.is_empty() {
422 return Some(name.to_string());
423 }
424 }
425 }
426 None
427}
428
429#[allow(unreachable_patterns)]
444impl From<yang_db::DbError> for BaseError {
445 fn from(err: yang_db::DbError) -> Self {
446 use yang_db::DbError as D;
447 match &err {
448 D::QueryError(_)
450 | D::TableNotFound(_)
451 | D::TypeConversionError(_)
452 | D::DeserializationError(_)
453 | D::UnsupportedOperator(_)
454 | D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
455
456 D::DatabaseError(info) => match info.kind() {
460 yang_db::SqlErrorKind::UniqueViolation => {
461 let field = info
462 .constraint()
463 .and_then(|constraint| constraint.rsplit('.').next())
464 .map(str::to_string)
465 .or_else(|| duplicate_key_field(info.message()))
466 .unwrap_or_else(|| "unknown".to_string());
467 BaseError::ParamInvalid(field, "该值已存在".to_string())
468 }
469 yang_db::SqlErrorKind::UndefinedTable => BaseError::DatabaseQueryFailed(err),
470 yang_db::SqlErrorKind::ConnectionFailure
471 | yang_db::SqlErrorKind::TooManyConnections => {
472 BaseError::DatabaseConnectionDbError(err)
473 }
474 _ => BaseError::DatabaseExecuteFailed(err),
475 },
476
477 D::PoolClosed => BaseError::DatabaseConnectionDbError(err),
479
480 D::ConstraintError(message) => match duplicate_key_field(message) {
483 Some(field) => BaseError::ParamInvalid(field, "该值已存在".to_string()),
484 None => BaseError::DatabaseExecuteFailed(err),
485 },
486
487 D::SqlSyntaxError(_)
489 | D::MissingWhereClause
490 | D::MissingGroupByClause
491 | D::InvalidArgument(_)
492 | D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
493
494 D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
496
497 D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
499
500 D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
502
503 D::RedisCommandError(_)
505 | D::RedisPoolError(_)
506 | D::RedisPoolClosed
507 | D::RedisError(_)
508 | D::RedisTypeConversionError(_)
509 | D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
510
511 _ => BaseError::DatabaseQueryFailed(err),
513 }
514 }
515}
516
517impl From<std::io::Error> for BaseError {
519 fn from(err: std::io::Error) -> Self {
520 BaseError::IoError(err.to_string())
521 }
522}
523
524impl From<serde_json::Error> for BaseError {
526 fn from(err: serde_json::Error) -> Self {
527 if err.is_syntax() || err.is_data() || err.is_eof() {
528 BaseError::JsonDeserializeFailed(err.to_string())
529 } else {
530 BaseError::JsonSerializeFailed(err.to_string())
531 }
532 }
533}
534
535#[cfg(feature = "http")]
537impl From<reqwest::Error> for BaseError {
538 fn from(err: reqwest::Error) -> Self {
539 if err.is_timeout() {
540 BaseError::HttpTimeout
541 } else {
542 BaseError::HttpRequestFailed(err)
546 }
547 }
548}
549
550#[cfg(feature = "token")]
557impl From<jsonwebtoken::errors::Error> for BaseError {
558 fn from(err: jsonwebtoken::errors::Error) -> Self {
559 use jsonwebtoken::errors::ErrorKind;
560 match err.kind() {
561 ErrorKind::ExpiredSignature => BaseError::TokenExpired,
562 ErrorKind::InvalidToken
563 | ErrorKind::InvalidSignature
564 | ErrorKind::InvalidIssuer
565 | ErrorKind::InvalidAudience
566 | ErrorKind::InvalidSubject
567 | ErrorKind::InvalidAlgorithm
568 | ErrorKind::MissingAlgorithm
569 | ErrorKind::ImmatureSignature
570 | ErrorKind::MissingRequiredClaim(_)
571 | ErrorKind::InvalidEcdsaKey
572 | ErrorKind::InvalidRsaKey(_)
573 | ErrorKind::InvalidKeyFormat
574 | ErrorKind::RsaFailedSigning
575 | ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
576 ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
578 BaseError::TokenParseFailed(err)
579 }
580 _ => BaseError::TokenVerifyFailed(err),
582 }
583 }
584}
585
586#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594#[non_exhaustive]
595pub enum ErrorCategory {
596 Client,
598 Auth,
600 NotFound,
602 Conflict,
604 Transient,
609 Server,
611}
612
613pub const NOT_READY_CODE: i32 = 900001;
618
619impl BaseError {
620 pub fn code(&self) -> i32 {
649 match self {
650 BaseError::PluginAlreadyRegistered(_) => 100001,
652 BaseError::PluginNotFound(_) => 100002,
653 BaseError::PluginRegisterFailed(_, _) => 100003,
654 BaseError::PluginInitFailed(_, _) => 100004,
655 BaseError::PluginDependencyMissing(_, _) => 100005,
656 BaseError::PluginCircularDependency(_) => 100006,
657 BaseError::PluginConfigInvalid(_, _) => 100007,
658 BaseError::PluginShutdownFailed(_, _) => 100008,
659 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
660 crate::plugin::PluginLifecycleStage::Register => 100003,
661 crate::plugin::PluginLifecycleStage::Initialize => 100004,
662 crate::plugin::PluginLifecycleStage::Shutdown => 100008,
663 },
664
665 BaseError::DatabaseConnectionFailed(_) => 200001,
667 BaseError::DatabaseConnectionDbError(_) => 200011,
668 BaseError::DatabaseAlreadyInitialized => 200002,
669 BaseError::DatabaseQueryFailed(_) => 200003,
670 BaseError::DatabaseExecuteFailed(_) => 200004,
671 BaseError::DatabaseInitFailed(_) => 200005,
672 BaseError::DatabaseNotInitialized => 200008,
673 BaseError::DatabaseTransactionFailed(_) => 200009,
674 BaseError::MissingWhereClause(_) => 200010,
675 BaseError::UnsupportedCapability(_) => 200012,
676
677 BaseError::RedisConnectionFailed(_) => 210001,
679 BaseError::RedisAlreadyInitialized => 210002,
680 BaseError::RedisNotInitialized => 210003,
681 BaseError::RedisOperationFailed(_) => 210004,
682 BaseError::RedisOperationDbError(_) => 210011,
683
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::HttpResponseTooLarge { .. } => 300008,
693 BaseError::UpstreamUnavailable(_) => 300009,
696
697 BaseError::TokenKeyInvalid(_) => 400001,
699 BaseError::TokenGenerateFailed(_) => 400002,
700 BaseError::TokenVerifyFailed(_) => 400003,
701 BaseError::TokenParseFailed(_) => 400004,
702 BaseError::TokenExpired => 400005,
703 BaseError::TokenTypeInvalid(_) => 400006,
704 BaseError::TokenRevoked => 400007,
705 BaseError::TokenRevocationStateInvalid(_) => 400008,
706 BaseError::AuthorizationStale => 400009,
707 BaseError::AuthorizationVersionInvalid => 400010,
708 BaseError::AuthorizationCheckUnavailable => 400011,
709
710 BaseError::JsonSerializeFailed(_) => 500001,
712 BaseError::JsonDeserializeFailed(_) => 500002,
713
714 BaseError::InvalidFieldType(_, _) => 600001,
716 BaseError::InvalidEnumValue(_, _) => 600002,
717 BaseError::StringTooLong(_, _, _) => 600003,
718 BaseError::InvalidJsonFormat(_, _) => 600004,
719 BaseError::ValidationFailed(_, _) => 600005,
720 BaseError::FieldRequired(_) => 600006,
721 BaseError::FieldNotFound(_, _) => 600007,
722 BaseError::FieldPermissionDenied(_, _, _) => 600008,
723
724 BaseError::ActionNotFound(_) => 700001,
726 BaseError::PermissionDenied(_) => 700002,
727 BaseError::Unauthorized(_) => 700003,
728 BaseError::ParamMissing(_) => 700004,
729 BaseError::ParamInvalid(_, _) => 700005,
730 BaseError::RecordNotFound(_) => 700006,
731 BaseError::UserNotFound(_) => 700007,
732 BaseError::InvalidPassword => 700008,
733 BaseError::TableDefinitionNotSet => 700009,
734 #[cfg(feature = "token")]
735 BaseError::StepUpRequired(_) => 700010,
736 BaseError::RateLimitExceeded { .. } => 700011,
737 BaseError::SecondFactorRequired => 700012,
738
739 BaseError::ConfigError(_) => 900001,
741 BaseError::IoError(_) => 900002,
742 BaseError::Unknown(_) => 999999,
743 }
744 }
745
746 pub fn code_str(&self) -> &'static str {
753 match self {
754 BaseError::PluginAlreadyRegistered(_) => "100001",
756 BaseError::PluginNotFound(_) => "100002",
757 BaseError::PluginRegisterFailed(_, _) => "100003",
758 BaseError::PluginInitFailed(_, _) => "100004",
759 BaseError::PluginDependencyMissing(_, _) => "100005",
760 BaseError::PluginCircularDependency(_) => "100006",
761 BaseError::PluginConfigInvalid(_, _) => "100007",
762 BaseError::PluginShutdownFailed(_, _) => "100008",
763 BaseError::PluginLifecycleFailed { stage, .. } => match stage {
764 crate::plugin::PluginLifecycleStage::Register => "100003",
765 crate::plugin::PluginLifecycleStage::Initialize => "100004",
766 crate::plugin::PluginLifecycleStage::Shutdown => "100008",
767 },
768 BaseError::DatabaseConnectionFailed(_) => "200001",
770 BaseError::DatabaseConnectionDbError(_) => "200011",
771 BaseError::DatabaseAlreadyInitialized => "200002",
772 BaseError::DatabaseQueryFailed(_) => "200003",
773 BaseError::DatabaseExecuteFailed(_) => "200004",
774 BaseError::DatabaseInitFailed(_) => "200005",
775 BaseError::DatabaseNotInitialized => "200008",
776 BaseError::DatabaseTransactionFailed(_) => "200009",
777 BaseError::MissingWhereClause(_) => "200010",
778 BaseError::UnsupportedCapability(_) => "200012",
779 BaseError::RedisConnectionFailed(_) => "210001",
781 BaseError::RedisAlreadyInitialized => "210002",
782 BaseError::RedisNotInitialized => "210003",
783 BaseError::RedisOperationFailed(_) => "210004",
784 BaseError::RedisOperationDbError(_) => "210011",
785 BaseError::HttpClientCreateFailed(_) => "300001",
787 BaseError::HttpRequestFailed(_) => "300002",
788 BaseError::HttpResponseParseFailed(_) => "300003",
789 BaseError::HttpTimeout => "300004",
790 BaseError::HttpClientAlreadyInitialized => "300005",
791 BaseError::HttpClientNotInitialized => "300006",
792 BaseError::HttpCircuitBreakerOpen(_) => "300007",
793 BaseError::HttpResponseTooLarge { .. } => "300008",
794 BaseError::UpstreamUnavailable(_) => "300009",
795 BaseError::TokenKeyInvalid(_) => "400001",
797 BaseError::TokenGenerateFailed(_) => "400002",
798 BaseError::TokenVerifyFailed(_) => "400003",
799 BaseError::TokenParseFailed(_) => "400004",
800 BaseError::TokenExpired => "400005",
801 BaseError::TokenTypeInvalid(_) => "400006",
802 BaseError::TokenRevoked => "400007",
803 BaseError::TokenRevocationStateInvalid(_) => "400008",
804 BaseError::AuthorizationStale => "400009",
805 BaseError::AuthorizationVersionInvalid => "400010",
806 BaseError::AuthorizationCheckUnavailable => "400011",
807 BaseError::JsonSerializeFailed(_) => "500001",
809 BaseError::JsonDeserializeFailed(_) => "500002",
810 BaseError::InvalidFieldType(_, _) => "600001",
812 BaseError::InvalidEnumValue(_, _) => "600002",
813 BaseError::StringTooLong(_, _, _) => "600003",
814 BaseError::InvalidJsonFormat(_, _) => "600004",
815 BaseError::ValidationFailed(_, _) => "600005",
816 BaseError::FieldRequired(_) => "600006",
817 BaseError::FieldNotFound(_, _) => "600007",
818 BaseError::FieldPermissionDenied(_, _, _) => "600008",
819 BaseError::ActionNotFound(_) => "700001",
821 BaseError::PermissionDenied(_) => "700002",
822 BaseError::Unauthorized(_) => "700003",
823 BaseError::ParamMissing(_) => "700004",
824 BaseError::ParamInvalid(_, _) => "700005",
825 BaseError::RecordNotFound(_) => "700006",
826 BaseError::UserNotFound(_) => "700007",
827 BaseError::InvalidPassword => "700008",
828 BaseError::TableDefinitionNotSet => "700009",
829 #[cfg(feature = "token")]
830 BaseError::StepUpRequired(_) => "700010",
831 BaseError::RateLimitExceeded { .. } => "700011",
832 BaseError::SecondFactorRequired => "700012",
833 BaseError::ConfigError(_) => "900001",
835 BaseError::IoError(_) => "900002",
836 BaseError::Unknown(_) => "999999",
837 }
838 }
839
840 pub fn category(&self) -> ErrorCategory {
850 use ErrorCategory as C;
851 match self {
852 BaseError::PluginAlreadyRegistered(_) => C::Conflict,
854 BaseError::PluginCircularDependency(_) => C::Client,
855 BaseError::PluginDependencyMissing(_, _) => C::Client,
856 BaseError::PluginConfigInvalid(_, _) => C::Client,
857 BaseError::PluginNotFound(_)
858 | BaseError::PluginRegisterFailed(_, _)
859 | BaseError::PluginInitFailed(_, _)
860 | BaseError::PluginShutdownFailed(_, _)
861 | BaseError::PluginLifecycleFailed { .. } => C::Server,
862 BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
865 C::Transient
866 }
867 BaseError::MissingWhereClause(_) => C::Client,
868 BaseError::UnsupportedCapability(_) => C::Server,
869 BaseError::DatabaseAlreadyInitialized
870 | BaseError::DatabaseNotInitialized
871 | BaseError::DatabaseInitFailed(_) => C::Server,
872 BaseError::DatabaseQueryFailed(_)
874 | BaseError::DatabaseExecuteFailed(_)
875 | BaseError::DatabaseTransactionFailed(_) => C::Server,
876 BaseError::RedisConnectionFailed(_) => C::Transient,
878 BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
879 BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
880 match source.category() {
881 yang_db::DbErrorCategory::Transient => C::Transient,
882 yang_db::DbErrorCategory::Conflict => C::Conflict,
883 yang_db::DbErrorCategory::Client => C::Client,
884 yang_db::DbErrorCategory::NotFound => C::NotFound,
885 yang_db::DbErrorCategory::Server => C::Server,
886 _ => C::Server,
887 }
888 }
889 BaseError::HttpClientCreateFailed(_)
891 | BaseError::HttpClientNotInitialized
892 | BaseError::HttpClientAlreadyInitialized => C::Client,
893 BaseError::HttpResponseParseFailed(_) => C::Client,
895 BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
896 BaseError::UpstreamUnavailable(_) => C::Transient,
898 BaseError::HttpCircuitBreakerOpen(_) => C::Server,
900 BaseError::HttpResponseTooLarge { .. } => C::Server,
902 BaseError::TokenKeyInvalid(_)
904 | BaseError::TokenGenerateFailed(_)
905 | BaseError::TokenTypeInvalid(_)
906 | BaseError::TokenParseFailed(_) => C::Client,
907 BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
908 C::Auth
909 }
910 BaseError::TokenRevocationStateInvalid(_) => C::Server,
911 BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
912 BaseError::AuthorizationCheckUnavailable => C::Transient,
913 BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
915 BaseError::InvalidFieldType(_, _)
917 | BaseError::InvalidEnumValue(_, _)
918 | BaseError::StringTooLong(_, _, _)
919 | BaseError::InvalidJsonFormat(_, _)
920 | BaseError::ValidationFailed(_, _)
921 | BaseError::FieldRequired(_)
922 | BaseError::FieldPermissionDenied(_, _, _) => C::Client,
923 BaseError::FieldNotFound(_, _) => C::NotFound,
924 BaseError::Unauthorized(_)
926 | BaseError::PermissionDenied(_)
927 | BaseError::SecondFactorRequired => C::Auth,
928 BaseError::ParamMissing(_)
929 | BaseError::ParamInvalid(_, _)
930 | BaseError::RateLimitExceeded { .. } => C::Client,
931 BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
932 BaseError::InvalidPassword => C::Auth,
933 BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
934 #[cfg(feature = "token")]
935 BaseError::StepUpRequired(_) => C::Client,
936 BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
938 }
939 }
940
941 fn db_error(&self) -> Option<&yang_db::DbError> {
943 match self {
944 BaseError::DatabaseConnectionFailed(err)
945 | BaseError::DatabaseConnectionDbError(err)
946 | BaseError::DatabaseQueryFailed(err)
947 | BaseError::DatabaseExecuteFailed(err)
948 | BaseError::DatabaseTransactionFailed(err)
949 | BaseError::RedisConnectionFailed(err)
950 | BaseError::RedisOperationFailed(err)
951 | BaseError::RedisOperationDbError(err) => Some(err),
952 _ => None,
953 }
954 }
955
956 pub fn sql_error_info(&self) -> Option<&yang_db::SqlErrorInfo> {
961 match self.db_error()? {
962 yang_db::DbError::DatabaseError(info) => Some(info.as_ref()),
963 _ => None,
964 }
965 }
966
967 pub fn sqlstate(&self) -> Option<&str> {
969 self.sql_error_info().map(yang_db::SqlErrorInfo::code)
970 }
971
972 pub fn constraint(&self) -> Option<&str> {
974 self.sql_error_info()
975 .and_then(yang_db::SqlErrorInfo::constraint)
976 }
977
978 pub fn is_retryable(&self) -> bool {
984 self.db_error().map_or_else(
985 || self.category() == ErrorCategory::Transient,
986 |err| err.is_retryable(),
987 )
988 }
989
990 pub fn is_transaction_aborted(&self) -> bool {
994 self.sql_error_info()
995 .is_some_and(|info| info.kind() == yang_db::SqlErrorKind::InFailedTransaction)
996 }
997
998 pub fn is_timeout(&self) -> bool {
1001 matches!(self, BaseError::HttpTimeout)
1002 || self.sql_error_info().is_some_and(|info| {
1003 matches!(
1004 info.kind(),
1005 yang_db::SqlErrorKind::QueryCanceled | yang_db::SqlErrorKind::LockNotAvailable
1006 )
1007 })
1008 }
1009
1010 pub fn is_client_error(&self) -> bool {
1016 matches!(
1017 self.category(),
1018 ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
1019 )
1020 }
1021
1022 pub fn is_server_error(&self) -> bool {
1028 matches!(
1029 self.category(),
1030 ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
1031 )
1032 }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037 use super::*;
1038
1039 #[test]
1040 fn test_not_ready_code_is_stable() {
1041 assert_eq!(NOT_READY_CODE, 900001);
1042 }
1043
1044 #[test]
1045 fn test_error_codes_plugin() {
1046 assert_eq!(
1047 BaseError::PluginAlreadyRegistered("test".to_string()).code(),
1048 100001
1049 );
1050 assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
1051 assert_eq!(
1052 BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
1053 100003
1054 );
1055 assert_eq!(
1056 BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
1057 100004
1058 );
1059 assert_eq!(
1060 BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
1061 100005
1062 );
1063 assert_eq!(
1064 BaseError::PluginCircularDependency("test".to_string()).code(),
1065 100006
1066 );
1067 assert_eq!(
1068 BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
1069 100007
1070 );
1071 assert_eq!(
1072 BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
1073 100008
1074 );
1075 }
1076
1077 #[test]
1078 fn test_error_codes_database() {
1079 assert_eq!(
1080 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
1081 "reason".to_string()
1082 ))
1083 .code(),
1084 200001
1085 );
1086 assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
1087 assert_eq!(
1088 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
1089 .code(),
1090 200003
1091 );
1092 assert_eq!(
1093 BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
1094 .code(),
1095 200004
1096 );
1097 assert_eq!(
1098 BaseError::DatabaseInitFailed("reason".to_string()).code(),
1099 200005
1100 );
1101 assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
1102 assert_eq!(
1103 BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
1104 "reason".to_string()
1105 ))
1106 .code(),
1107 200009
1108 );
1109 }
1110
1111 #[cfg(feature = "http")]
1112 #[test]
1113 fn test_error_codes_http() {
1114 assert_eq!(
1116 BaseError::HttpResponseParseFailed("reason".to_string()).code(),
1117 300003
1118 );
1119 assert_eq!(BaseError::HttpTimeout.code(), 300004);
1120 assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
1121 assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
1122 }
1123
1124 #[cfg(feature = "token")]
1125 #[test]
1126 fn test_error_codes_token() {
1127 assert_eq!(
1128 BaseError::TokenKeyInvalid("reason".to_string()).code(),
1129 400001
1130 );
1131 assert_eq!(
1132 BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
1133 jsonwebtoken::errors::ErrorKind::InvalidToken
1134 ))
1135 .code(),
1136 400002
1137 );
1138 assert_eq!(
1139 BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
1140 jsonwebtoken::errors::ErrorKind::InvalidToken
1141 ))
1142 .code(),
1143 400003
1144 );
1145 assert_eq!(
1146 BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
1147 jsonwebtoken::errors::ErrorKind::InvalidToken
1148 ))
1149 .code(),
1150 400004
1151 );
1152 assert_eq!(BaseError::TokenExpired.code(), 400005);
1153 assert_eq!(
1154 BaseError::TokenTypeInvalid("reason".to_string()).code(),
1155 400006
1156 );
1157 }
1158
1159 #[test]
1160 fn test_error_codes_serialization() {
1161 assert_eq!(
1162 BaseError::JsonSerializeFailed("reason".to_string()).code(),
1163 500001
1164 );
1165 assert_eq!(
1166 BaseError::JsonDeserializeFailed("reason".to_string()).code(),
1167 500002
1168 );
1169 }
1170
1171 #[test]
1172 fn test_error_codes_field_validation() {
1173 assert_eq!(
1174 BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
1175 600001
1176 );
1177 assert_eq!(
1178 BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
1179 600002
1180 );
1181 assert_eq!(
1182 BaseError::StringTooLong("field".to_string(), 100, 50).code(),
1183 600003
1184 );
1185 assert_eq!(
1186 BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
1187 600004
1188 );
1189 assert_eq!(
1190 BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
1191 600005
1192 );
1193 assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
1194 assert_eq!(
1195 BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
1196 600007
1197 );
1198 assert_eq!(
1199 BaseError::FieldPermissionDenied(
1200 "table".to_string(),
1201 "field".to_string(),
1202 "reason".to_string()
1203 )
1204 .code(),
1205 600008
1206 );
1207 }
1208
1209 #[test]
1210 fn test_error_codes_action_system() {
1211 assert_eq!(
1212 BaseError::ActionNotFound("test_action".to_string()).code(),
1213 700001
1214 );
1215 assert_eq!(
1216 BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
1217 700002
1218 );
1219 assert_eq!(
1220 BaseError::Unauthorized("Token 无效".to_string()).code(),
1221 700003
1222 );
1223 assert_eq!(
1224 BaseError::ParamMissing("user_id".to_string()).code(),
1225 700004
1226 );
1227 assert_eq!(
1228 BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
1229 700005
1230 );
1231 assert_eq!(
1232 BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
1233 700006
1234 );
1235 assert_eq!(
1236 BaseError::UserNotFound("user_123".to_string()).code(),
1237 700007
1238 );
1239 assert_eq!(BaseError::InvalidPassword.code(), 700008);
1240 assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
1241 assert_eq!(
1242 BaseError::RateLimitExceeded {
1243 retry_after_seconds: 30
1244 }
1245 .code(),
1246 700011
1247 );
1248 assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
1249 assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
1250 }
1251
1252 #[test]
1253 fn test_error_codes_general() {
1254 assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
1255 assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
1256 assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
1257 }
1258
1259 #[test]
1260 fn test_all_error_codes_are_nonzero() {
1261 let errors: Vec<BaseError> = vec![
1263 BaseError::PluginNotFound("test".to_string()),
1264 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
1265 BaseError::HttpTimeout,
1266 BaseError::TokenExpired,
1267 BaseError::JsonSerializeFailed("test".to_string()),
1268 BaseError::FieldRequired("test".to_string()),
1269 BaseError::ActionNotFound("test".to_string()),
1270 BaseError::PermissionDenied("test".to_string()),
1271 BaseError::Unauthorized("test".to_string()),
1272 BaseError::ParamMissing("test".to_string()),
1273 BaseError::RecordNotFound("test".to_string()),
1274 BaseError::UserNotFound("test".to_string()),
1275 BaseError::InvalidPassword,
1276 BaseError::TableDefinitionNotSet,
1277 BaseError::RateLimitExceeded {
1278 retry_after_seconds: 30,
1279 },
1280 BaseError::Unknown("test".to_string()),
1281 ];
1282
1283 for error in errors {
1284 assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
1285 }
1286 }
1287
1288 #[test]
1290 fn test_database_error_source_chain() {
1291 use std::error::Error;
1292
1293 let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
1294 let base_err = BaseError::DatabaseQueryFailed(db_err);
1295
1296 let source = base_err.source();
1298 assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
1299 }
1300
1301 #[test]
1303 fn test_from_db_error_preserves_source() {
1304 use std::error::Error;
1305
1306 let db_err = yang_db::DbError::QueryError("查询失败".to_string());
1307 let base_err: BaseError = db_err.into();
1308
1309 assert!(base_err.source().is_some());
1311 assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
1312 }
1313
1314 #[test]
1315 fn test_redis_connection_and_operation_errors_preserve_db_source() {
1316 use std::error::Error;
1317
1318 let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
1319 "connection refused".into(),
1320 ));
1321 let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
1322 "WRONGTYPE".into(),
1323 ));
1324
1325 assert_eq!(connection.code(), 210001);
1326 assert_eq!(operation.code(), 210004);
1327 assert!(connection.source().is_some());
1328 assert!(operation.source().is_some());
1329 }
1330
1331 #[test]
1332 fn test_plugin_lifecycle_error_preserves_stage_and_source() {
1333 use std::error::Error;
1334
1335 let error = BaseError::PluginLifecycleFailed {
1336 plugin: "audit".into(),
1337 stage: crate::plugin::PluginLifecycleStage::Shutdown,
1338 source: Box::new(std::io::Error::other("flush failed")),
1339 };
1340
1341 assert_eq!(error.code(), 100008);
1342 assert_eq!(error.code_str(), "100008");
1343 assert!(error.to_string().contains("audit"));
1344 assert!(error.to_string().contains("shutdown"));
1345 assert!(error.source().is_some());
1346 }
1347
1348 #[test]
1350 fn test_code_str_matches_code() {
1351 let samples: Vec<BaseError> = vec![
1353 BaseError::PluginNotFound("p".into()),
1354 BaseError::PluginLifecycleFailed {
1355 plugin: "p".into(),
1356 stage: crate::plugin::PluginLifecycleStage::Initialize,
1357 source: Box::new(std::io::Error::other("init")),
1358 },
1359 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
1360 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
1361 BaseError::DatabaseNotInitialized,
1362 BaseError::RedisNotInitialized,
1363 BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
1364 BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
1365 BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
1366 BaseError::HttpTimeout,
1367 BaseError::TokenExpired,
1368 BaseError::TokenRevoked,
1369 BaseError::TokenRevocationStateInvalid("invalid".into()),
1370 BaseError::AuthorizationStale,
1371 BaseError::AuthorizationVersionInvalid,
1372 BaseError::AuthorizationCheckUnavailable,
1373 BaseError::JsonSerializeFailed("s".into()),
1374 BaseError::FieldNotFound("t".into(), "f".into()),
1375 BaseError::ParamInvalid("k".into(), "r".into()),
1376 BaseError::TableDefinitionNotSet,
1377 BaseError::RateLimitExceeded {
1378 retry_after_seconds: 30,
1379 },
1380 BaseError::SecondFactorRequired,
1381 BaseError::ConfigError("c".into()),
1382 BaseError::Unknown("u".into()),
1383 ];
1384 for err in samples {
1385 let code = err.code();
1386 let code_str = err.code_str();
1387 assert_eq!(
1388 code_str.parse::<i32>().unwrap(),
1389 code,
1390 "code_str {:?} 与 code {} 不一致(变体 {:?})",
1391 code_str,
1392 code,
1393 err
1394 );
1395 }
1396 }
1397
1398 #[test]
1400 fn test_error_category_coverage() {
1401 assert_eq!(
1403 BaseError::ParamInvalid("k".into(), "r".into()).category(),
1404 ErrorCategory::Client
1405 );
1406 assert_eq!(
1407 BaseError::ValidationFailed("f".into(), "r".into()).category(),
1408 ErrorCategory::Client
1409 );
1410 assert_eq!(
1412 BaseError::Unauthorized("u".into()).category(),
1413 ErrorCategory::Auth
1414 );
1415 assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
1416 assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
1417 assert_eq!(
1418 BaseError::SecondFactorRequired.category(),
1419 ErrorCategory::Auth
1420 );
1421 assert_eq!(
1423 BaseError::RecordNotFound("r".into()).category(),
1424 ErrorCategory::NotFound
1425 );
1426 assert_eq!(
1427 BaseError::FieldNotFound("t".into(), "f".into()).category(),
1428 ErrorCategory::NotFound
1429 );
1430 assert_eq!(
1432 BaseError::PluginAlreadyRegistered("p".into()).category(),
1433 ErrorCategory::Conflict
1434 );
1435 assert_eq!(
1437 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1438 .category(),
1439 ErrorCategory::Transient
1440 );
1441 assert_eq!(
1442 BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
1443 .category(),
1444 ErrorCategory::Transient
1445 );
1446 assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
1447 assert_eq!(
1449 BaseError::Unknown("u".into()).category(),
1450 ErrorCategory::Server
1451 );
1452 assert_eq!(
1453 BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
1454 ErrorCategory::Server
1455 );
1456 }
1457
1458 #[test]
1460 fn test_is_retryable() {
1461 assert!(
1462 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1463 .is_retryable()
1464 );
1465 assert!(BaseError::HttpTimeout.is_retryable());
1466 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
1467 assert!(!BaseError::Unauthorized("u".into()).is_retryable());
1468 assert!(!BaseError::Unknown("u".into()).is_retryable());
1469 }
1470
1471 #[test]
1473 fn test_is_client_error() {
1474 assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
1475 assert!(BaseError::Unauthorized("u".into()).is_client_error());
1476 assert!(BaseError::TokenExpired.is_client_error());
1477 assert!(BaseError::RecordNotFound("r".into()).is_client_error());
1478 assert!(BaseError::ActionNotFound("a".into()).is_client_error());
1479 assert!(
1480 !BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1481 .is_client_error()
1482 );
1483 assert!(!BaseError::Unknown("u".into()).is_client_error());
1484 }
1485
1486 #[test]
1488 fn test_is_server_error() {
1489 assert!(BaseError::Unknown("u".into()).is_server_error());
1490 assert!(
1491 BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
1492 .is_server_error()
1493 );
1494 assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
1495 assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
1496 assert!(!BaseError::Unauthorized("u".into()).is_server_error());
1497 }
1498
1499 #[test]
1501 fn mysql_duplicate_entry_maps_to_param_invalid_naming_the_key() {
1502 let error = BaseError::from(yang_db::DbError::ConstraintError(
1506 "Duplicate entry 'payment_currency' for key 'source_key'".to_string(),
1507 ));
1508 match error {
1509 BaseError::ParamInvalid(field, message) => {
1510 assert_eq!(field, "source_key", "要点名冲突的键");
1511 assert!(!message.is_empty());
1512 }
1513 other => panic!("唯一键冲突应映射为 ParamInvalid,实际: {other:?}"),
1514 }
1515 }
1516
1517 #[test]
1519 fn qualified_mysql_key_name_keeps_only_the_last_segment() {
1520 assert_eq!(
1521 duplicate_key_field(
1522 "Duplicate entry 'x' for key 'yang_system.feishu_datasource.source_key'"
1523 ),
1524 Some("source_key".to_string())
1525 );
1526 }
1527
1528 #[test]
1530 fn postgres_unique_violation_maps_to_param_invalid() {
1531 let error = BaseError::from(yang_db::DbError::ConstraintError(
1532 "duplicate key value violates unique constraint \"feishu_option_option_id_key\""
1533 .to_string(),
1534 ));
1535 match error {
1536 BaseError::ParamInvalid(field, _) => assert_eq!(field, "feishu_option_option_id_key"),
1537 other => panic!("PG 唯一约束冲突应映射为 ParamInvalid,实际: {other:?}"),
1538 }
1539 }
1540
1541 #[test]
1546 fn other_constraint_errors_keep_their_own_mapping() {
1547 for message in [
1548 "Cannot add or update a child row: a foreign key constraint fails",
1549 "Column 'title' cannot be null",
1550 "Check constraint 'positive_amount' is violated",
1551 ] {
1552 let error = BaseError::from(yang_db::DbError::ConstraintError(message.to_string()));
1553 assert!(
1554 !matches!(error, BaseError::ParamInvalid(_, _)),
1555 "{message:?} 不该被当成参数非法,实际: {error:?}"
1556 );
1557 }
1558 }
1559
1560 #[test]
1562 fn duplicate_key_field_returns_none_for_unrecognised_messages() {
1563 assert_eq!(duplicate_key_field(""), None);
1564 assert_eq!(
1565 duplicate_key_field("Duplicate entry 'x'"),
1566 None,
1567 "缺 for key 段就该放弃提取,而不是编一个名字出来"
1568 );
1569 assert_eq!(duplicate_key_field("some other db error"), None);
1570 }
1571
1572 fn sql_error(code: &str, constraint: Option<&str>) -> BaseError {
1573 let mut info = yang_db::SqlErrorInfo::new(code, format!("sqlstate {code}"));
1574 if let Some(constraint) = constraint {
1575 info = info.with_constraint(Some(constraint.to_string()));
1576 }
1577 BaseError::DatabaseExecuteFailed(yang_db::DbError::DatabaseError(Box::new(info)))
1578 }
1579
1580 #[test]
1583 fn sqlstate_semantics_are_exposed_from_wrapped_db_error() {
1584 for code in ["40001", "40P01"] {
1586 let error = sql_error(code, None);
1587 assert!(error.is_retryable(), "{code} 应可重试");
1588 assert!(!error.is_timeout(), "{code} 不是超时");
1589 assert!(!error.is_transaction_aborted(), "{code} 不是事务中止");
1590 }
1591
1592 assert!(sql_error("08006", None).is_retryable());
1594 assert!(sql_error("53300", None).is_retryable());
1595
1596 for code in ["55P03", "57014"] {
1598 let error = sql_error(code, None);
1599 assert!(!error.is_retryable(), "{code} 不应自动重试");
1600 assert!(error.is_timeout(), "{code} 应识别为超时/取消");
1601 }
1602
1603 let aborted = sql_error("25P02", None);
1605 assert!(aborted.is_transaction_aborted());
1606 assert!(!aborted.is_retryable());
1607 assert!(!aborted.is_timeout());
1608 assert!(!sql_error("40001", None).is_transaction_aborted());
1609 }
1610
1611 #[test]
1613 fn constraint_errors_keep_sqlstate_and_constraint_context() {
1614 let foreign_key = sql_error("23503", Some("orders_user_id_fkey"));
1615 assert_eq!(foreign_key.sqlstate(), Some("23503"));
1616 assert_eq!(foreign_key.constraint(), Some("orders_user_id_fkey"));
1617 assert!(!foreign_key.is_retryable());
1618 assert!(foreign_key.is_server_error());
1619
1620 let not_null = sql_error("23502", Some("users_email_not_null"));
1621 assert_eq!(not_null.sqlstate(), Some("23502"));
1622 assert_eq!(not_null.constraint(), Some("users_email_not_null"));
1623
1624 let check = sql_error("23514", Some("positive_amount"));
1625 assert_eq!(check.constraint(), Some("positive_amount"));
1626
1627 let plain = BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("boom".into()));
1629 assert_eq!(plain.sqlstate(), None);
1630 assert_eq!(plain.constraint(), None);
1631 }
1632}