use thiserror::Error;
pub type Result<T, E = BaseError> = std::result::Result<T, E>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BaseError {
#[error("插件已注册: {0}")]
PluginAlreadyRegistered(String),
#[error("插件未找到: {0}")]
PluginNotFound(String),
#[error("插件注册失败 [{0}]: {1}")]
PluginRegisterFailed(String, String),
#[error("插件初始化失败 [{0}]: {1}")]
PluginInitFailed(String, String),
#[error("插件依赖缺失 [{0}]: 缺少依赖 {1}")]
PluginDependencyMissing(String, String),
#[error("插件循环依赖: {0}")]
PluginCircularDependency(String),
#[error("插件配置无效 [{0}]: {1}")]
PluginConfigInvalid(String, String),
#[error("插件关闭失败 [{0}]: {1}")]
PluginShutdownFailed(String, String),
#[error("插件生命周期失败 [{plugin}] ({stage}): {source}")]
PluginLifecycleFailed {
plugin: String,
stage: crate::plugin::PluginLifecycleStage,
#[source]
source: crate::plugin::PluginError,
},
#[error("数据库连接失败 [DbError]: {0}")]
DatabaseConnectionFailed(#[source] yang_db::DbError),
#[error("数据库连接失败 [DbError]: {0}")]
DatabaseConnectionDbError(#[source] yang_db::DbError),
#[error("数据库已初始化")]
DatabaseAlreadyInitialized,
#[error("数据库查询失败: {0}")]
DatabaseQueryFailed(#[source] yang_db::DbError),
#[error("数据库执行失败: {0}")]
DatabaseExecuteFailed(#[source] yang_db::DbError),
#[error("数据库初始化失败: {0}")]
DatabaseInitFailed(String),
#[error("数据库未初始化")]
DatabaseNotInitialized,
#[error("数据库事务失败: {0}")]
DatabaseTransactionFailed(#[source] yang_db::DbError),
#[error("当前后端不支持该能力: {0}")]
UnsupportedCapability(String),
#[error("事务与表数据源不一致 [{table}]: 期望 {expected},实际 {actual}")]
DatasourceMismatch {
table: String,
expected: String,
actual: String,
},
#[error("UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作: {0}")]
MissingWhereClause(String),
#[error("Redis 连接失败: {0}")]
RedisConnectionFailed(#[source] yang_db::DbError),
#[error("Redis 已初始化")]
RedisAlreadyInitialized,
#[error("Redis 未初始化")]
RedisNotInitialized,
#[error("Redis 操作失败: {0}")]
RedisOperationFailed(#[source] yang_db::DbError),
#[error("Redis 操作失败: {0}")]
RedisOperationDbError(#[source] yang_db::DbError),
#[cfg(feature = "http")]
#[error("HTTP 客户端创建失败: {0}")]
HttpClientCreateFailed(#[source] reqwest::Error),
#[cfg(not(feature = "http"))]
#[error("HTTP 客户端创建失败: {0}")]
HttpClientCreateFailed(String),
#[cfg(feature = "http")]
#[error("HTTP 请求失败: {0}")]
HttpRequestFailed(#[source] reqwest::Error),
#[cfg(not(feature = "http"))]
#[error("HTTP 请求失败: {0}")]
HttpRequestFailed(String),
#[error("HTTP 响应解析失败: {0}")]
HttpResponseParseFailed(String),
#[error("HTTP 响应体超过上限: 上限 {limit} 字节, 实际 {actual:?} 字节")]
HttpResponseTooLarge {
limit: usize,
actual: Option<u64>,
},
#[error("HTTP 请求超时")]
HttpTimeout,
#[error("HTTP 客户端已初始化")]
HttpClientAlreadyInitialized,
#[error("HTTP 客户端未初始化")]
HttpClientNotInitialized,
#[error("HTTP 熔断器已打开,目标主机暂不可用: {0}")]
HttpCircuitBreakerOpen(String),
#[error("上游服务暂不可用: {0}")]
UpstreamUnavailable(String),
#[error("Token 密钥无效: {0}")]
TokenKeyInvalid(String),
#[cfg(feature = "token")]
#[error("Token 生成失败: {0}")]
TokenGenerateFailed(#[source] jsonwebtoken::errors::Error),
#[cfg(not(feature = "token"))]
#[error("Token 生成失败: {0}")]
TokenGenerateFailed(String),
#[cfg(feature = "token")]
#[error("Token 验证失败: {0}")]
TokenVerifyFailed(#[source] jsonwebtoken::errors::Error),
#[cfg(not(feature = "token"))]
#[error("Token 验证失败: {0}")]
TokenVerifyFailed(String),
#[cfg(feature = "token")]
#[error("Token 解析失败: {0}")]
TokenParseFailed(#[source] jsonwebtoken::errors::Error),
#[cfg(not(feature = "token"))]
#[error("Token 解析失败: {0}")]
TokenParseFailed(String),
#[error("Token 已过期")]
TokenExpired,
#[error("Token 已被撤销")]
TokenRevoked,
#[error("Token 撤销状态无效: {0}")]
TokenRevocationStateInvalid(String),
#[error("授权状态已变更,请刷新登录")]
AuthorizationStale,
#[error("授权版本无效")]
AuthorizationVersionInvalid,
#[error("授权状态暂时无法校验")]
AuthorizationCheckUnavailable,
#[error("Token 类型无效: {0}")]
TokenTypeInvalid(String),
#[error("JSON 序列化失败: {0}")]
JsonSerializeFailed(String),
#[error("JSON 反序列化失败: {0}")]
JsonDeserializeFailed(String),
#[error("字段类型无效 [{0}]: {1}")]
InvalidFieldType(String, String),
#[error("枚举值无效 [{0}]: 值 '{1}' 不在可选值列表中")]
InvalidEnumValue(String, String),
#[error("字符串长度超出限制 [{0}]: 当前长度 {1},最大长度 {2}")]
StringTooLong(String, usize, usize),
#[error("JSON 格式无效 [{0}]: {1}")]
InvalidJsonFormat(String, String),
#[error("验证失败 [{0}]: {1}")]
ValidationFailed(String, String),
#[error("字段必填: {0}")]
FieldRequired(String),
#[error("字段未找到 [表: {0}]: {1}")]
FieldNotFound(String, String),
#[error("字段权限被拒绝 [表: {0}, 字段: {1}]: {2}")]
FieldPermissionDenied(String, String, String),
#[error("Action 未找到: {0}")]
ActionNotFound(String),
#[error("权限被拒绝: {0}")]
PermissionDenied(String),
#[error("未授权: {0}")]
Unauthorized(String),
#[error("参数缺失: {0}")]
ParamMissing(String),
#[error("参数无效 [{0}]: {1}")]
ParamInvalid(String, String),
#[error("请求过于频繁,请在 {retry_after_seconds} 秒后重试")]
RateLimitExceeded {
retry_after_seconds: u64,
},
#[error("需要输入双重验证码")]
SecondFactorRequired,
#[error("记录未找到: {0}")]
RecordNotFound(String),
#[error("用户未找到: {0}")]
UserNotFound(String),
#[error("密码无效")]
InvalidPassword,
#[error("表定义未设置")]
TableDefinitionNotSet,
#[cfg(feature = "token")]
#[error("敏感操作需要重新认证")]
StepUpRequired(crate::action::StepUpChallenge),
#[error("配置错误: {0}")]
ConfigError(String),
#[error("IO 错误: {0}")]
IoError(String),
#[error("未知错误: {0}")]
Unknown(String),
}
fn duplicate_key_field(message: &str) -> Option<String> {
if message.contains("Duplicate entry") {
if let Some((_, rest)) = message.split_once("for key '") {
let raw = rest.split('\'').next().unwrap_or_default();
let last = raw.rsplit('.').next().unwrap_or(raw);
if !last.is_empty() {
return Some(last.to_string());
}
}
}
if message.contains("duplicate key value violates unique constraint") {
if let Some((_, rest)) = message.split_once("unique constraint \"") {
let name = rest.split('"').next().unwrap_or_default();
if !name.is_empty() {
return Some(name.to_string());
}
}
}
None
}
#[allow(unreachable_patterns)]
impl From<yang_db::DbError> for BaseError {
fn from(err: yang_db::DbError) -> Self {
use yang_db::DbError as D;
match &err {
D::QueryError(_)
| D::TableNotFound(_)
| D::TypeConversionError(_)
| D::DeserializationError(_)
| D::UnsupportedOperator(_)
| D::Unknown(_) => BaseError::DatabaseQueryFailed(err),
D::DatabaseError(info) => match info.kind() {
yang_db::SqlErrorKind::UniqueViolation => {
let field = info
.constraint()
.and_then(|constraint| constraint.rsplit('.').next())
.map(str::to_string)
.or_else(|| duplicate_key_field(info.message()))
.unwrap_or_else(|| "unknown".to_string());
BaseError::ParamInvalid(field, "该值已存在".to_string())
}
yang_db::SqlErrorKind::UndefinedTable => BaseError::DatabaseQueryFailed(err),
yang_db::SqlErrorKind::ConnectionFailure
| yang_db::SqlErrorKind::TooManyConnections => {
BaseError::DatabaseConnectionDbError(err)
}
_ => BaseError::DatabaseExecuteFailed(err),
},
D::PoolClosed => BaseError::DatabaseConnectionDbError(err),
D::ConstraintError(message) => match duplicate_key_field(message) {
Some(field) => BaseError::ParamInvalid(field, "该值已存在".to_string()),
None => BaseError::DatabaseExecuteFailed(err),
},
D::SqlSyntaxError(_)
| D::MissingWhereClause
| D::MissingGroupByClause
| D::InvalidArgument(_)
| D::SerializationError(_) => BaseError::DatabaseExecuteFailed(err),
D::TransactionError(_) => BaseError::DatabaseTransactionFailed(err),
D::ConnectionError(_) => BaseError::DatabaseConnectionDbError(err),
D::RedisConnectionError(_) => BaseError::RedisConnectionFailed(err),
D::RedisCommandError(_)
| D::RedisPoolError(_)
| D::RedisPoolClosed
| D::RedisError(_)
| D::RedisTypeConversionError(_)
| D::RedisTimeoutError(_) => BaseError::RedisOperationFailed(err),
_ => BaseError::DatabaseQueryFailed(err),
}
}
}
impl From<std::io::Error> for BaseError {
fn from(err: std::io::Error) -> Self {
BaseError::IoError(err.to_string())
}
}
impl From<serde_json::Error> for BaseError {
fn from(err: serde_json::Error) -> Self {
if err.is_syntax() || err.is_data() || err.is_eof() {
BaseError::JsonDeserializeFailed(err.to_string())
} else {
BaseError::JsonSerializeFailed(err.to_string())
}
}
}
#[cfg(feature = "http")]
impl From<reqwest::Error> for BaseError {
fn from(err: reqwest::Error) -> Self {
if err.is_timeout() {
BaseError::HttpTimeout
} else {
BaseError::HttpRequestFailed(err)
}
}
}
#[cfg(feature = "token")]
impl From<jsonwebtoken::errors::Error> for BaseError {
fn from(err: jsonwebtoken::errors::Error) -> Self {
use jsonwebtoken::errors::ErrorKind;
match err.kind() {
ErrorKind::ExpiredSignature => BaseError::TokenExpired,
ErrorKind::InvalidToken
| ErrorKind::InvalidSignature
| ErrorKind::InvalidIssuer
| ErrorKind::InvalidAudience
| ErrorKind::InvalidSubject
| ErrorKind::InvalidAlgorithm
| ErrorKind::MissingAlgorithm
| ErrorKind::ImmatureSignature
| ErrorKind::MissingRequiredClaim(_)
| ErrorKind::InvalidEcdsaKey
| ErrorKind::InvalidRsaKey(_)
| ErrorKind::InvalidKeyFormat
| ErrorKind::RsaFailedSigning
| ErrorKind::InvalidAlgorithmName => BaseError::TokenVerifyFailed(err),
ErrorKind::Base64(_) | ErrorKind::Json(_) | ErrorKind::Utf8(_) => {
BaseError::TokenParseFailed(err)
}
_ => BaseError::TokenVerifyFailed(err),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorCategory {
Client,
Auth,
NotFound,
Conflict,
Transient,
Server,
}
pub const NOT_READY_CODE: i32 = 900001;
impl BaseError {
pub fn code(&self) -> i32 {
match self {
BaseError::PluginAlreadyRegistered(_) => 100001,
BaseError::PluginNotFound(_) => 100002,
BaseError::PluginRegisterFailed(_, _) => 100003,
BaseError::PluginInitFailed(_, _) => 100004,
BaseError::PluginDependencyMissing(_, _) => 100005,
BaseError::PluginCircularDependency(_) => 100006,
BaseError::PluginConfigInvalid(_, _) => 100007,
BaseError::PluginShutdownFailed(_, _) => 100008,
BaseError::PluginLifecycleFailed { stage, .. } => match stage {
crate::plugin::PluginLifecycleStage::Register => 100003,
crate::plugin::PluginLifecycleStage::Initialize => 100004,
crate::plugin::PluginLifecycleStage::Shutdown => 100008,
},
BaseError::DatabaseConnectionFailed(_) => 200001,
BaseError::DatabaseConnectionDbError(_) => 200011,
BaseError::DatabaseAlreadyInitialized => 200002,
BaseError::DatabaseQueryFailed(_) => 200003,
BaseError::DatabaseExecuteFailed(_) => 200004,
BaseError::DatabaseInitFailed(_) => 200005,
BaseError::DatabaseNotInitialized => 200008,
BaseError::DatabaseTransactionFailed(_) => 200009,
BaseError::MissingWhereClause(_) => 200010,
BaseError::UnsupportedCapability(_) => 200012,
BaseError::DatasourceMismatch { .. } => 200013,
BaseError::RedisConnectionFailed(_) => 210001,
BaseError::RedisAlreadyInitialized => 210002,
BaseError::RedisNotInitialized => 210003,
BaseError::RedisOperationFailed(_) => 210004,
BaseError::RedisOperationDbError(_) => 210011,
BaseError::HttpClientCreateFailed(_) => 300001,
BaseError::HttpRequestFailed(_) => 300002,
BaseError::HttpResponseParseFailed(_) => 300003,
BaseError::HttpTimeout => 300004,
BaseError::HttpClientAlreadyInitialized => 300005,
BaseError::HttpClientNotInitialized => 300006,
BaseError::HttpCircuitBreakerOpen(_) => 300007,
BaseError::HttpResponseTooLarge { .. } => 300008,
BaseError::UpstreamUnavailable(_) => 300009,
BaseError::TokenKeyInvalid(_) => 400001,
BaseError::TokenGenerateFailed(_) => 400002,
BaseError::TokenVerifyFailed(_) => 400003,
BaseError::TokenParseFailed(_) => 400004,
BaseError::TokenExpired => 400005,
BaseError::TokenTypeInvalid(_) => 400006,
BaseError::TokenRevoked => 400007,
BaseError::TokenRevocationStateInvalid(_) => 400008,
BaseError::AuthorizationStale => 400009,
BaseError::AuthorizationVersionInvalid => 400010,
BaseError::AuthorizationCheckUnavailable => 400011,
BaseError::JsonSerializeFailed(_) => 500001,
BaseError::JsonDeserializeFailed(_) => 500002,
BaseError::InvalidFieldType(_, _) => 600001,
BaseError::InvalidEnumValue(_, _) => 600002,
BaseError::StringTooLong(_, _, _) => 600003,
BaseError::InvalidJsonFormat(_, _) => 600004,
BaseError::ValidationFailed(_, _) => 600005,
BaseError::FieldRequired(_) => 600006,
BaseError::FieldNotFound(_, _) => 600007,
BaseError::FieldPermissionDenied(_, _, _) => 600008,
BaseError::ActionNotFound(_) => 700001,
BaseError::PermissionDenied(_) => 700002,
BaseError::Unauthorized(_) => 700003,
BaseError::ParamMissing(_) => 700004,
BaseError::ParamInvalid(_, _) => 700005,
BaseError::RecordNotFound(_) => 700006,
BaseError::UserNotFound(_) => 700007,
BaseError::InvalidPassword => 700008,
BaseError::TableDefinitionNotSet => 700009,
#[cfg(feature = "token")]
BaseError::StepUpRequired(_) => 700010,
BaseError::RateLimitExceeded { .. } => 700011,
BaseError::SecondFactorRequired => 700012,
BaseError::ConfigError(_) => 900001,
BaseError::IoError(_) => 900002,
BaseError::Unknown(_) => 999999,
}
}
pub fn code_str(&self) -> &'static str {
match self {
BaseError::PluginAlreadyRegistered(_) => "100001",
BaseError::PluginNotFound(_) => "100002",
BaseError::PluginRegisterFailed(_, _) => "100003",
BaseError::PluginInitFailed(_, _) => "100004",
BaseError::PluginDependencyMissing(_, _) => "100005",
BaseError::PluginCircularDependency(_) => "100006",
BaseError::PluginConfigInvalid(_, _) => "100007",
BaseError::PluginShutdownFailed(_, _) => "100008",
BaseError::PluginLifecycleFailed { stage, .. } => match stage {
crate::plugin::PluginLifecycleStage::Register => "100003",
crate::plugin::PluginLifecycleStage::Initialize => "100004",
crate::plugin::PluginLifecycleStage::Shutdown => "100008",
},
BaseError::DatabaseConnectionFailed(_) => "200001",
BaseError::DatabaseConnectionDbError(_) => "200011",
BaseError::DatabaseAlreadyInitialized => "200002",
BaseError::DatabaseQueryFailed(_) => "200003",
BaseError::DatabaseExecuteFailed(_) => "200004",
BaseError::DatabaseInitFailed(_) => "200005",
BaseError::DatabaseNotInitialized => "200008",
BaseError::DatabaseTransactionFailed(_) => "200009",
BaseError::MissingWhereClause(_) => "200010",
BaseError::UnsupportedCapability(_) => "200012",
BaseError::DatasourceMismatch { .. } => "200013",
BaseError::RedisConnectionFailed(_) => "210001",
BaseError::RedisAlreadyInitialized => "210002",
BaseError::RedisNotInitialized => "210003",
BaseError::RedisOperationFailed(_) => "210004",
BaseError::RedisOperationDbError(_) => "210011",
BaseError::HttpClientCreateFailed(_) => "300001",
BaseError::HttpRequestFailed(_) => "300002",
BaseError::HttpResponseParseFailed(_) => "300003",
BaseError::HttpTimeout => "300004",
BaseError::HttpClientAlreadyInitialized => "300005",
BaseError::HttpClientNotInitialized => "300006",
BaseError::HttpCircuitBreakerOpen(_) => "300007",
BaseError::HttpResponseTooLarge { .. } => "300008",
BaseError::UpstreamUnavailable(_) => "300009",
BaseError::TokenKeyInvalid(_) => "400001",
BaseError::TokenGenerateFailed(_) => "400002",
BaseError::TokenVerifyFailed(_) => "400003",
BaseError::TokenParseFailed(_) => "400004",
BaseError::TokenExpired => "400005",
BaseError::TokenTypeInvalid(_) => "400006",
BaseError::TokenRevoked => "400007",
BaseError::TokenRevocationStateInvalid(_) => "400008",
BaseError::AuthorizationStale => "400009",
BaseError::AuthorizationVersionInvalid => "400010",
BaseError::AuthorizationCheckUnavailable => "400011",
BaseError::JsonSerializeFailed(_) => "500001",
BaseError::JsonDeserializeFailed(_) => "500002",
BaseError::InvalidFieldType(_, _) => "600001",
BaseError::InvalidEnumValue(_, _) => "600002",
BaseError::StringTooLong(_, _, _) => "600003",
BaseError::InvalidJsonFormat(_, _) => "600004",
BaseError::ValidationFailed(_, _) => "600005",
BaseError::FieldRequired(_) => "600006",
BaseError::FieldNotFound(_, _) => "600007",
BaseError::FieldPermissionDenied(_, _, _) => "600008",
BaseError::ActionNotFound(_) => "700001",
BaseError::PermissionDenied(_) => "700002",
BaseError::Unauthorized(_) => "700003",
BaseError::ParamMissing(_) => "700004",
BaseError::ParamInvalid(_, _) => "700005",
BaseError::RecordNotFound(_) => "700006",
BaseError::UserNotFound(_) => "700007",
BaseError::InvalidPassword => "700008",
BaseError::TableDefinitionNotSet => "700009",
#[cfg(feature = "token")]
BaseError::StepUpRequired(_) => "700010",
BaseError::RateLimitExceeded { .. } => "700011",
BaseError::SecondFactorRequired => "700012",
BaseError::ConfigError(_) => "900001",
BaseError::IoError(_) => "900002",
BaseError::Unknown(_) => "999999",
}
}
pub fn category(&self) -> ErrorCategory {
use ErrorCategory as C;
match self {
BaseError::PluginAlreadyRegistered(_) => C::Conflict,
BaseError::PluginCircularDependency(_) => C::Client,
BaseError::PluginDependencyMissing(_, _) => C::Client,
BaseError::PluginConfigInvalid(_, _) => C::Client,
BaseError::PluginNotFound(_)
| BaseError::PluginRegisterFailed(_, _)
| BaseError::PluginInitFailed(_, _)
| BaseError::PluginShutdownFailed(_, _)
| BaseError::PluginLifecycleFailed { .. } => C::Server,
BaseError::DatabaseConnectionFailed(_) | BaseError::DatabaseConnectionDbError(_) => {
C::Transient
}
BaseError::MissingWhereClause(_) => C::Client,
BaseError::UnsupportedCapability(_) => C::Server,
BaseError::DatabaseAlreadyInitialized
| BaseError::DatabaseNotInitialized
| BaseError::DatabaseInitFailed(_)
| BaseError::DatasourceMismatch { .. } => C::Server,
BaseError::DatabaseQueryFailed(_)
| BaseError::DatabaseExecuteFailed(_)
| BaseError::DatabaseTransactionFailed(_) => C::Server,
BaseError::RedisConnectionFailed(_) => C::Transient,
BaseError::RedisAlreadyInitialized | BaseError::RedisNotInitialized => C::Server,
BaseError::RedisOperationFailed(source) | BaseError::RedisOperationDbError(source) => {
match source.category() {
yang_db::DbErrorCategory::Transient => C::Transient,
yang_db::DbErrorCategory::Conflict => C::Conflict,
yang_db::DbErrorCategory::Client => C::Client,
yang_db::DbErrorCategory::NotFound => C::NotFound,
yang_db::DbErrorCategory::Server => C::Server,
_ => C::Server,
}
}
BaseError::HttpClientCreateFailed(_)
| BaseError::HttpClientNotInitialized
| BaseError::HttpClientAlreadyInitialized => C::Client,
BaseError::HttpResponseParseFailed(_) => C::Client,
BaseError::HttpRequestFailed(_) | BaseError::HttpTimeout => C::Transient,
BaseError::UpstreamUnavailable(_) => C::Transient,
BaseError::HttpCircuitBreakerOpen(_) => C::Server,
BaseError::HttpResponseTooLarge { .. } => C::Server,
BaseError::TokenKeyInvalid(_)
| BaseError::TokenGenerateFailed(_)
| BaseError::TokenTypeInvalid(_)
| BaseError::TokenParseFailed(_) => C::Client,
BaseError::TokenExpired | BaseError::TokenRevoked | BaseError::TokenVerifyFailed(_) => {
C::Auth
}
BaseError::TokenRevocationStateInvalid(_) => C::Server,
BaseError::AuthorizationStale | BaseError::AuthorizationVersionInvalid => C::Auth,
BaseError::AuthorizationCheckUnavailable => C::Transient,
BaseError::JsonSerializeFailed(_) | BaseError::JsonDeserializeFailed(_) => C::Client,
BaseError::InvalidFieldType(_, _)
| BaseError::InvalidEnumValue(_, _)
| BaseError::StringTooLong(_, _, _)
| BaseError::InvalidJsonFormat(_, _)
| BaseError::ValidationFailed(_, _)
| BaseError::FieldRequired(_)
| BaseError::FieldPermissionDenied(_, _, _) => C::Client,
BaseError::FieldNotFound(_, _) => C::NotFound,
BaseError::Unauthorized(_)
| BaseError::PermissionDenied(_)
| BaseError::SecondFactorRequired => C::Auth,
BaseError::ParamMissing(_)
| BaseError::ParamInvalid(_, _)
| BaseError::RateLimitExceeded { .. } => C::Client,
BaseError::RecordNotFound(_) | BaseError::UserNotFound(_) => C::NotFound,
BaseError::InvalidPassword => C::Auth,
BaseError::ActionNotFound(_) | BaseError::TableDefinitionNotSet => C::NotFound,
#[cfg(feature = "token")]
BaseError::StepUpRequired(_) => C::Client,
BaseError::ConfigError(_) | BaseError::IoError(_) | BaseError::Unknown(_) => C::Server,
}
}
fn db_error(&self) -> Option<&yang_db::DbError> {
match self {
BaseError::DatabaseConnectionFailed(err)
| BaseError::DatabaseConnectionDbError(err)
| BaseError::DatabaseQueryFailed(err)
| BaseError::DatabaseExecuteFailed(err)
| BaseError::DatabaseTransactionFailed(err)
| BaseError::RedisConnectionFailed(err)
| BaseError::RedisOperationFailed(err)
| BaseError::RedisOperationDbError(err) => Some(err),
_ => None,
}
}
pub fn sql_error_info(&self) -> Option<&yang_db::SqlErrorInfo> {
match self.db_error()? {
yang_db::DbError::DatabaseError(info) => Some(info.as_ref()),
_ => None,
}
}
pub fn sqlstate(&self) -> Option<&str> {
self.sql_error_info().map(yang_db::SqlErrorInfo::code)
}
pub fn constraint(&self) -> Option<&str> {
self.sql_error_info()
.and_then(yang_db::SqlErrorInfo::constraint)
}
pub fn is_retryable(&self) -> bool {
self.db_error().map_or_else(
|| self.category() == ErrorCategory::Transient,
|err| err.is_retryable(),
)
}
pub fn is_transaction_aborted(&self) -> bool {
self.sql_error_info()
.is_some_and(|info| info.kind() == yang_db::SqlErrorKind::InFailedTransaction)
}
pub fn is_timeout(&self) -> bool {
matches!(self, BaseError::HttpTimeout)
|| self.sql_error_info().is_some_and(|info| {
matches!(
info.kind(),
yang_db::SqlErrorKind::QueryCanceled | yang_db::SqlErrorKind::LockNotAvailable
)
})
}
pub fn is_client_error(&self) -> bool {
matches!(
self.category(),
ErrorCategory::Client | ErrorCategory::Auth | ErrorCategory::NotFound
)
}
pub fn is_server_error(&self) -> bool {
matches!(
self.category(),
ErrorCategory::Server | ErrorCategory::Transient | ErrorCategory::Conflict
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_not_ready_code_is_stable() {
assert_eq!(NOT_READY_CODE, 900001);
}
#[test]
fn test_error_codes_plugin() {
assert_eq!(
BaseError::PluginAlreadyRegistered("test".to_string()).code(),
100001
);
assert_eq!(BaseError::PluginNotFound("test".to_string()).code(), 100002);
assert_eq!(
BaseError::PluginRegisterFailed("test".to_string(), "reason".to_string()).code(),
100003
);
assert_eq!(
BaseError::PluginInitFailed("test".to_string(), "reason".to_string()).code(),
100004
);
assert_eq!(
BaseError::PluginDependencyMissing("test".to_string(), "dep".to_string()).code(),
100005
);
assert_eq!(
BaseError::PluginCircularDependency("test".to_string()).code(),
100006
);
assert_eq!(
BaseError::PluginConfigInvalid("test".to_string(), "reason".to_string()).code(),
100007
);
assert_eq!(
BaseError::PluginShutdownFailed("test".to_string(), "reason".to_string()).code(),
100008
);
}
#[test]
fn test_error_codes_database() {
assert_eq!(
BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError(
"reason".to_string()
))
.code(),
200001
);
assert_eq!(BaseError::DatabaseAlreadyInitialized.code(), 200002);
assert_eq!(
BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("reason".to_string()))
.code(),
200003
);
assert_eq!(
BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("reason".to_string()))
.code(),
200004
);
assert_eq!(
BaseError::DatabaseInitFailed("reason".to_string()).code(),
200005
);
assert_eq!(BaseError::DatabaseNotInitialized.code(), 200008);
assert_eq!(
BaseError::DatabaseTransactionFailed(yang_db::DbError::TransactionError(
"reason".to_string()
))
.code(),
200009
);
}
#[cfg(feature = "http")]
#[test]
fn test_error_codes_http() {
assert_eq!(
BaseError::HttpResponseParseFailed("reason".to_string()).code(),
300003
);
assert_eq!(BaseError::HttpTimeout.code(), 300004);
assert_eq!(BaseError::HttpClientAlreadyInitialized.code(), 300005);
assert_eq!(BaseError::HttpClientNotInitialized.code(), 300006);
}
#[cfg(feature = "token")]
#[test]
fn test_error_codes_token() {
assert_eq!(
BaseError::TokenKeyInvalid("reason".to_string()).code(),
400001
);
assert_eq!(
BaseError::TokenGenerateFailed(jsonwebtoken::errors::Error::from(
jsonwebtoken::errors::ErrorKind::InvalidToken
))
.code(),
400002
);
assert_eq!(
BaseError::TokenVerifyFailed(jsonwebtoken::errors::Error::from(
jsonwebtoken::errors::ErrorKind::InvalidToken
))
.code(),
400003
);
assert_eq!(
BaseError::TokenParseFailed(jsonwebtoken::errors::Error::from(
jsonwebtoken::errors::ErrorKind::InvalidToken
))
.code(),
400004
);
assert_eq!(BaseError::TokenExpired.code(), 400005);
assert_eq!(
BaseError::TokenTypeInvalid("reason".to_string()).code(),
400006
);
}
#[test]
fn test_error_codes_serialization() {
assert_eq!(
BaseError::JsonSerializeFailed("reason".to_string()).code(),
500001
);
assert_eq!(
BaseError::JsonDeserializeFailed("reason".to_string()).code(),
500002
);
}
#[test]
fn test_error_codes_field_validation() {
assert_eq!(
BaseError::InvalidFieldType("field".to_string(), "reason".to_string()).code(),
600001
);
assert_eq!(
BaseError::InvalidEnumValue("field".to_string(), "value".to_string()).code(),
600002
);
assert_eq!(
BaseError::StringTooLong("field".to_string(), 100, 50).code(),
600003
);
assert_eq!(
BaseError::InvalidJsonFormat("field".to_string(), "reason".to_string()).code(),
600004
);
assert_eq!(
BaseError::ValidationFailed("field".to_string(), "reason".to_string()).code(),
600005
);
assert_eq!(BaseError::FieldRequired("field".to_string()).code(), 600006);
assert_eq!(
BaseError::FieldNotFound("table".to_string(), "field".to_string()).code(),
600007
);
assert_eq!(
BaseError::FieldPermissionDenied(
"table".to_string(),
"field".to_string(),
"reason".to_string()
)
.code(),
600008
);
}
#[test]
fn test_error_codes_action_system() {
assert_eq!(
BaseError::ActionNotFound("test_action".to_string()).code(),
700001
);
assert_eq!(
BaseError::PermissionDenied("需要管理员权限".to_string()).code(),
700002
);
assert_eq!(
BaseError::Unauthorized("Token 无效".to_string()).code(),
700003
);
assert_eq!(
BaseError::ParamMissing("user_id".to_string()).code(),
700004
);
assert_eq!(
BaseError::ParamInvalid("age".to_string(), "必须是正整数".to_string()).code(),
700005
);
assert_eq!(
BaseError::RecordNotFound("用户 ID: 123".to_string()).code(),
700006
);
assert_eq!(
BaseError::UserNotFound("user_123".to_string()).code(),
700007
);
assert_eq!(BaseError::InvalidPassword.code(), 700008);
assert_eq!(BaseError::TableDefinitionNotSet.code(), 700009);
assert_eq!(
BaseError::RateLimitExceeded {
retry_after_seconds: 30
}
.code(),
700011
);
assert_eq!(BaseError::SecondFactorRequired.code(), 700012);
assert_eq!(BaseError::SecondFactorRequired.code_str(), "700012");
}
#[test]
fn test_error_codes_general() {
assert_eq!(BaseError::ConfigError("reason".to_string()).code(), 900001);
assert_eq!(BaseError::IoError("reason".to_string()).code(), 900002);
assert_eq!(BaseError::Unknown("reason".to_string()).code(), 999999);
}
#[test]
fn test_all_error_codes_are_nonzero() {
let errors: Vec<BaseError> = vec![
BaseError::PluginNotFound("test".to_string()),
BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("test".to_string())),
BaseError::HttpTimeout,
BaseError::TokenExpired,
BaseError::JsonSerializeFailed("test".to_string()),
BaseError::FieldRequired("test".to_string()),
BaseError::ActionNotFound("test".to_string()),
BaseError::PermissionDenied("test".to_string()),
BaseError::Unauthorized("test".to_string()),
BaseError::ParamMissing("test".to_string()),
BaseError::RecordNotFound("test".to_string()),
BaseError::UserNotFound("test".to_string()),
BaseError::InvalidPassword,
BaseError::TableDefinitionNotSet,
BaseError::RateLimitExceeded {
retry_after_seconds: 30,
},
BaseError::Unknown("test".to_string()),
];
for error in errors {
assert_ne!(error.code(), 0, "错误码不应该为 0: {:?}", error);
}
}
#[test]
fn test_database_error_source_chain() {
use std::error::Error;
let db_err = yang_db::DbError::QueryError("底层查询错误".to_string());
let base_err = BaseError::DatabaseQueryFailed(db_err);
let source = base_err.source();
assert!(source.is_some(), "BaseError.source() 应返回底层 DbError");
}
#[test]
fn test_from_db_error_preserves_source() {
use std::error::Error;
let db_err = yang_db::DbError::QueryError("查询失败".to_string());
let base_err: BaseError = db_err.into();
assert!(base_err.source().is_some());
assert!(matches!(base_err, BaseError::DatabaseQueryFailed(_)));
}
#[test]
fn test_redis_connection_and_operation_errors_preserve_db_source() {
use std::error::Error;
let connection = BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError(
"connection refused".into(),
));
let operation = BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError(
"WRONGTYPE".into(),
));
assert_eq!(connection.code(), 210001);
assert_eq!(operation.code(), 210004);
assert!(connection.source().is_some());
assert!(operation.source().is_some());
}
#[test]
fn test_plugin_lifecycle_error_preserves_stage_and_source() {
use std::error::Error;
let error = BaseError::PluginLifecycleFailed {
plugin: "audit".into(),
stage: crate::plugin::PluginLifecycleStage::Shutdown,
source: Box::new(std::io::Error::other("flush failed")),
};
assert_eq!(error.code(), 100008);
assert_eq!(error.code_str(), "100008");
assert!(error.to_string().contains("audit"));
assert!(error.to_string().contains("shutdown"));
assert!(error.source().is_some());
}
#[test]
fn test_code_str_matches_code() {
let samples: Vec<BaseError> = vec![
BaseError::PluginNotFound("p".into()),
BaseError::PluginLifecycleFailed {
plugin: "p".into(),
stage: crate::plugin::PluginLifecycleStage::Initialize,
source: Box::new(std::io::Error::other("init")),
},
BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into())),
BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into())),
BaseError::DatabaseNotInitialized,
BaseError::RedisNotInitialized,
BaseError::RedisConnectionFailed(yang_db::DbError::RedisConnectionError("c".into())),
BaseError::RedisOperationFailed(yang_db::DbError::RedisCommandError("o".into())),
BaseError::RedisOperationDbError(yang_db::DbError::RedisConnectionError("c".into())),
BaseError::HttpTimeout,
BaseError::TokenExpired,
BaseError::TokenRevoked,
BaseError::TokenRevocationStateInvalid("invalid".into()),
BaseError::AuthorizationStale,
BaseError::AuthorizationVersionInvalid,
BaseError::AuthorizationCheckUnavailable,
BaseError::JsonSerializeFailed("s".into()),
BaseError::FieldNotFound("t".into(), "f".into()),
BaseError::ParamInvalid("k".into(), "r".into()),
BaseError::TableDefinitionNotSet,
BaseError::RateLimitExceeded {
retry_after_seconds: 30,
},
BaseError::SecondFactorRequired,
BaseError::ConfigError("c".into()),
BaseError::Unknown("u".into()),
];
for err in samples {
let code = err.code();
let code_str = err.code_str();
assert_eq!(
code_str.parse::<i32>().unwrap(),
code,
"code_str {:?} 与 code {} 不一致(变体 {:?})",
code_str,
code,
err
);
}
}
#[test]
fn test_error_category_coverage() {
assert_eq!(
BaseError::ParamInvalid("k".into(), "r".into()).category(),
ErrorCategory::Client
);
assert_eq!(
BaseError::ValidationFailed("f".into(), "r".into()).category(),
ErrorCategory::Client
);
assert_eq!(
BaseError::Unauthorized("u".into()).category(),
ErrorCategory::Auth
);
assert_eq!(BaseError::TokenExpired.category(), ErrorCategory::Auth);
assert_eq!(BaseError::InvalidPassword.category(), ErrorCategory::Auth);
assert_eq!(
BaseError::SecondFactorRequired.category(),
ErrorCategory::Auth
);
assert_eq!(
BaseError::RecordNotFound("r".into()).category(),
ErrorCategory::NotFound
);
assert_eq!(
BaseError::FieldNotFound("t".into(), "f".into()).category(),
ErrorCategory::NotFound
);
assert_eq!(
BaseError::PluginAlreadyRegistered("p".into()).category(),
ErrorCategory::Conflict
);
assert_eq!(
BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
.category(),
ErrorCategory::Transient
);
assert_eq!(
BaseError::DatabaseConnectionDbError(yang_db::DbError::ConnectionError("c".into()))
.category(),
ErrorCategory::Transient
);
assert_eq!(BaseError::HttpTimeout.category(), ErrorCategory::Transient);
assert_eq!(
BaseError::Unknown("u".into()).category(),
ErrorCategory::Server
);
assert_eq!(
BaseError::DatabaseQueryFailed(yang_db::DbError::QueryError("q".into())).category(),
ErrorCategory::Server
);
}
#[test]
fn test_is_retryable() {
assert!(
BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
.is_retryable()
);
assert!(BaseError::HttpTimeout.is_retryable());
assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_retryable());
assert!(!BaseError::Unauthorized("u".into()).is_retryable());
assert!(!BaseError::Unknown("u".into()).is_retryable());
}
#[test]
fn test_is_client_error() {
assert!(BaseError::ParamInvalid("k".into(), "r".into()).is_client_error());
assert!(BaseError::Unauthorized("u".into()).is_client_error());
assert!(BaseError::TokenExpired.is_client_error());
assert!(BaseError::RecordNotFound("r".into()).is_client_error());
assert!(BaseError::ActionNotFound("a".into()).is_client_error());
assert!(
!BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
.is_client_error()
);
assert!(!BaseError::Unknown("u".into()).is_client_error());
}
#[test]
fn test_is_server_error() {
assert!(BaseError::Unknown("u".into()).is_server_error());
assert!(
BaseError::DatabaseConnectionFailed(yang_db::DbError::ConnectionError("c".into()))
.is_server_error()
);
assert!(BaseError::PluginAlreadyRegistered("p".into()).is_server_error());
assert!(!BaseError::ParamInvalid("k".into(), "r".into()).is_server_error());
assert!(!BaseError::Unauthorized("u".into()).is_server_error());
}
#[test]
fn mysql_duplicate_entry_maps_to_param_invalid_naming_the_key() {
let error = BaseError::from(yang_db::DbError::ConstraintError(
"Duplicate entry 'payment_currency' for key 'source_key'".to_string(),
));
match error {
BaseError::ParamInvalid(field, message) => {
assert_eq!(field, "source_key", "要点名冲突的键");
assert!(!message.is_empty());
}
other => panic!("唯一键冲突应映射为 ParamInvalid,实际: {other:?}"),
}
}
#[test]
fn qualified_mysql_key_name_keeps_only_the_last_segment() {
assert_eq!(
duplicate_key_field(
"Duplicate entry 'x' for key 'yang_system.feishu_datasource.source_key'"
),
Some("source_key".to_string())
);
}
#[test]
fn postgres_unique_violation_maps_to_param_invalid() {
let error = BaseError::from(yang_db::DbError::ConstraintError(
"duplicate key value violates unique constraint \"feishu_option_option_id_key\""
.to_string(),
));
match error {
BaseError::ParamInvalid(field, _) => assert_eq!(field, "feishu_option_option_id_key"),
other => panic!("PG 唯一约束冲突应映射为 ParamInvalid,实际: {other:?}"),
}
}
#[test]
fn other_constraint_errors_keep_their_own_mapping() {
for message in [
"Cannot add or update a child row: a foreign key constraint fails",
"Column 'title' cannot be null",
"Check constraint 'positive_amount' is violated",
] {
let error = BaseError::from(yang_db::DbError::ConstraintError(message.to_string()));
assert!(
!matches!(error, BaseError::ParamInvalid(_, _)),
"{message:?} 不该被当成参数非法,实际: {error:?}"
);
}
}
#[test]
fn duplicate_key_field_returns_none_for_unrecognised_messages() {
assert_eq!(duplicate_key_field(""), None);
assert_eq!(
duplicate_key_field("Duplicate entry 'x'"),
None,
"缺 for key 段就该放弃提取,而不是编一个名字出来"
);
assert_eq!(duplicate_key_field("some other db error"), None);
}
fn sql_error(code: &str, constraint: Option<&str>) -> BaseError {
let mut info = yang_db::SqlErrorInfo::new(code, format!("sqlstate {code}"));
if let Some(constraint) = constraint {
info = info.with_constraint(Some(constraint.to_string()));
}
BaseError::DatabaseExecuteFailed(yang_db::DbError::DatabaseError(Box::new(info)))
}
#[test]
fn sqlstate_semantics_are_exposed_from_wrapped_db_error() {
for code in ["40001", "40P01"] {
let error = sql_error(code, None);
assert!(error.is_retryable(), "{code} 应可重试");
assert!(!error.is_timeout(), "{code} 不是超时");
assert!(!error.is_transaction_aborted(), "{code} 不是事务中止");
}
assert!(sql_error("08006", None).is_retryable());
assert!(sql_error("53300", None).is_retryable());
for code in ["55P03", "57014"] {
let error = sql_error(code, None);
assert!(!error.is_retryable(), "{code} 不应自动重试");
assert!(error.is_timeout(), "{code} 应识别为超时/取消");
}
let aborted = sql_error("25P02", None);
assert!(aborted.is_transaction_aborted());
assert!(!aborted.is_retryable());
assert!(!aborted.is_timeout());
assert!(!sql_error("40001", None).is_transaction_aborted());
}
#[test]
fn constraint_errors_keep_sqlstate_and_constraint_context() {
let foreign_key = sql_error("23503", Some("orders_user_id_fkey"));
assert_eq!(foreign_key.sqlstate(), Some("23503"));
assert_eq!(foreign_key.constraint(), Some("orders_user_id_fkey"));
assert!(!foreign_key.is_retryable());
assert!(foreign_key.is_server_error());
let not_null = sql_error("23502", Some("users_email_not_null"));
assert_eq!(not_null.sqlstate(), Some("23502"));
assert_eq!(not_null.constraint(), Some("users_email_not_null"));
let check = sql_error("23514", Some("positive_amount"));
assert_eq!(check.constraint(), Some("positive_amount"));
let plain = BaseError::DatabaseExecuteFailed(yang_db::DbError::QueryError("boom".into()));
assert_eq!(plain.sqlstate(), None);
assert_eq!(plain.constraint(), None);
}
}