Skip to main content

BaseError

Enum BaseError 

Source
#[non_exhaustive]
pub enum BaseError {
Show 70 variants PluginAlreadyRegistered(String), PluginNotFound(String), PluginRegisterFailed(String, String), PluginInitFailed(String, String), PluginDependencyMissing(String, String), PluginCircularDependency(String), PluginConfigInvalid(String, String), PluginShutdownFailed(String, String), PluginLifecycleFailed { plugin: String, stage: PluginLifecycleStage, source: PluginError, }, DatabaseConnectionFailed(DbError), DatabaseConnectionDbError(DbError), DatabaseAlreadyInitialized, DatabaseQueryFailed(DbError), DatabaseExecuteFailed(DbError), DatabaseInitFailed(String), DatabaseNotInitialized, DatabaseTransactionFailed(DbError), UnsupportedCapability(String), DatasourceMismatch { table: String, expected: String, actual: String, }, MissingWhereClause(String), RedisConnectionFailed(DbError), RedisAlreadyInitialized, RedisNotInitialized, RedisOperationFailed(DbError), RedisOperationDbError(DbError), HttpClientCreateFailed(Error), HttpRequestFailed(Error), HttpResponseParseFailed(String), HttpResponseTooLarge { limit: usize, actual: Option<u64>, }, HttpTimeout, HttpClientAlreadyInitialized, HttpClientNotInitialized, HttpCircuitBreakerOpen(String), UpstreamUnavailable(String), TokenKeyInvalid(String), TokenGenerateFailed(Error), TokenVerifyFailed(Error), TokenParseFailed(Error), TokenExpired, TokenRevoked, TokenRevocationStateInvalid(String), AuthorizationStale, AuthorizationVersionInvalid, AuthorizationCheckUnavailable, TokenTypeInvalid(String), JsonSerializeFailed(String), JsonDeserializeFailed(String), InvalidFieldType(String, String), InvalidEnumValue(String, String), StringTooLong(String, usize, usize), InvalidJsonFormat(String, String), ValidationFailed(String, String), FieldRequired(String), FieldNotFound(String, String), FieldPermissionDenied(String, String, String), ActionNotFound(String), PermissionDenied(String), Unauthorized(String), ParamMissing(String), ParamInvalid(String, String), RateLimitExceeded { retry_after_seconds: u64, }, SecondFactorRequired, RecordNotFound(String), UserNotFound(String), InvalidPassword, TableDefinitionNotSet, StepUpRequired(StepUpChallenge), ConfigError(String), IoError(String), Unknown(String),
}
Expand description

系统统一错误类型

包含所有模块的错误变体,使用中文错误消息

标注 #[non_exhaustive]:未来新增变体不构成跨 crate 破坏性变更(下游 match 需 带 _ 臂)。同 crate 内的穷举 match(code()/code_str()/category())不受 影响,新增变体时 test_code_str_matches_code 测试会捕获漏编。

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

PluginAlreadyRegistered(String)

插件已注册

§

PluginNotFound(String)

插件未找到

§

PluginRegisterFailed(String, String)

插件注册失败

§

PluginInitFailed(String, String)

插件初始化失败

§

PluginDependencyMissing(String, String)

插件依赖缺失

§

PluginCircularDependency(String)

插件循环依赖

§

PluginConfigInvalid(String, String)

插件配置无效

§

PluginShutdownFailed(String, String)

插件关闭失败

§

PluginLifecycleFailed

插件生命周期回调失败,保留插件名、阶段与底层错误链。

Fields

§plugin: String

插件名称。

§stage: PluginLifecycleStage

失败阶段。

§source: PluginError

插件回调或初始化操作返回的底层错误。

§

DatabaseConnectionFailed(DbError)

数据库连接失败,持有底层 DbError 以保留错误链

§

DatabaseConnectionDbError(DbError)

数据库连接失败(DbError 专用变体,用于 From<DbError> 映射)

与 DatabaseConnectionFailed 语义相同但独立编码 200011, 便于下游区分“直接构造的连接错误“和“来自 DbError 包装的连接错误“。

§

DatabaseAlreadyInitialized

数据库已初始化

§

DatabaseQueryFailed(DbError)

数据库查询失败,持有底层 DbError 以保留错误链

§

DatabaseExecuteFailed(DbError)

数据库执行失败,持有底层 DbError 以保留错误链

§

DatabaseInitFailed(String)

数据库初始化失败

§

DatabaseNotInitialized

数据库未初始化

§

DatabaseTransactionFailed(DbError)

数据库事务失败,持有底层 DbError 以保留错误链

§

UnsupportedCapability(String)

当前后端/构建不支持请求的能力(如方言专属语法)。

与 BaseError::ConfigError 区分:这是「运行时能力矩阵」的显式拒绝, 调用方应降级或换用受支持的入口,而不是修复配置。

§

DatasourceMismatch

表与事务不属于同一逻辑数据源。

Fields

§table: String

表名。

§expected: String

表所属数据源。

§actual: String

事务所属数据源(未标注时为 unscoped)。

§

MissingWhereClause(String)

UPDATE/DELETE 缺少 WHERE 条件,拒绝全表操作

与 yang-db 的 MissingWhereClause 安全网对齐:无 WHERE 的更新/删除 始终被拒绝,以防止误操作整表。

§

RedisConnectionFailed(DbError)

Redis 连接失败,持有底层 DbError 以保留错误链。

§

RedisAlreadyInitialized

Redis 已初始化

§

RedisNotInitialized

Redis 未初始化

§

RedisOperationFailed(DbError)

Redis 操作失败,持有底层 DbError 以保留错误链。

§

RedisOperationDbError(DbError)

Redis 操作失败,持有底层 DbError 以保留错误链

§

HttpClientCreateFailed(Error)

HTTP 客户端创建失败,持有底层 reqwest::Error 以保留错误链

§

HttpRequestFailed(Error)

HTTP 请求失败,持有底层 reqwest::Error 以保留错误链

§

HttpResponseParseFailed(String)

HTTP 响应解析失败

§

HttpResponseTooLarge

HTTP 响应体超过配置上限(防异常/恶意上游耗尽内存)

Fields

§limit: usize

配置的响应体上限(字节)。

§actual: Option<u64>

上游声明(Content-Length)的实际大小;流式累计触发时为 None。

§

HttpTimeout

HTTP 超时

§

HttpClientAlreadyInitialized

HTTP 客户端已初始化

§

HttpClientNotInitialized

HTTP 客户端未初始化

§

HttpCircuitBreakerOpen(String)

HTTP 熔断器打开:目标 host 近期连续失败,请求被快速拒绝

§

UpstreamUnavailable(String)

上游依赖暂时不可用(与具体传输无关)。

存在的理由:BaseError::HttpRequestFailed 在 http feature 开启时持有 reqwest::Error、关闭时持有 String,也就是说它的可构造性取决于 feature。 非 HTTP 传输(SMTP、消息队列等)需要同一语义的可重试错误,却又不能依赖该 feature —— 否则「上游暂时不可用」会随构建配置在「可重试」与「不可重试」之间 漂移(历史上邮件投递就因此从 503 退化成 500)。

分类是 ErrorCategory::Transient,在 HTTP 边界映射为 503, 语义上等同于 HttpRequestFailed,但不携带传输层错误链。

§

TokenKeyInvalid(String)

Token 密钥无效

§

TokenGenerateFailed(Error)

Token 生成失败,持有底层 jsonwebtoken::errors::Error 以保留错误链

§

TokenVerifyFailed(Error)

Token 验证失败,持有底层 jsonwebtoken::errors::Error 以保留错误链

§

TokenParseFailed(Error)

Token 解析失败,持有底层 jsonwebtoken::errors::Error 以保留错误链

§

TokenExpired

Token 已过期

§

TokenRevoked

Token 已被撤销(命中黑名单)

§

TokenRevocationStateInvalid(String)

Token 撤销状态损坏或返回结构不符合协议。

§

AuthorizationStale

Access Token 中的授权版本已落后于当前事实版本。

§

AuthorizationVersionInvalid

Access Token 中的授权版本缺失、非法或领先于事实版本。

§

AuthorizationCheckUnavailable

授权版本缓存与事实存储均无法完成请求时校验。

§

TokenTypeInvalid(String)

Token 类型无效

§

JsonSerializeFailed(String)

JSON 序列化失败

§

JsonDeserializeFailed(String)

JSON 反序列化失败

§

InvalidFieldType(String, String)

字段类型无效

§

InvalidEnumValue(String, String)

枚举值无效

§

StringTooLong(String, usize, usize)

字符串长度超出限制

§

InvalidJsonFormat(String, String)

JSON 格式无效

§

ValidationFailed(String, String)

验证失败

§

FieldRequired(String)

字段必填

§

FieldNotFound(String, String)

字段未找到

§

FieldPermissionDenied(String, String, String)

字段权限被拒绝

§

ActionNotFound(String)

Action 未找到

§

PermissionDenied(String)

权限被拒绝

§

Unauthorized(String)

未授权

§

ParamMissing(String)

参数缺失

§

ParamInvalid(String, String)

参数无效

§

RateLimitExceeded

请求超过速率限制。

Fields

§retry_after_seconds: u64

建议客户端等待的秒数。

§

SecondFactorRequired

第一因子已通过,需要第二因子(TOTP 动态码或恢复码)才能完成认证。

仅在密码校验通过后返回:客户端据此进入第二因子输入阶段 (两段式登录:账号密码 → 动态码),与 InvalidPassword 语义区分。

§

RecordNotFound(String)

记录未找到

§

UserNotFound(String)

用户未找到

§

InvalidPassword

密码无效

§

TableDefinitionNotSet

表定义未设置

§

StepUpRequired(StepUpChallenge)

敏感 Action 尚未完成短期重认证。

§

ConfigError(String)

配置错误

§

IoError(String)

IO 错误

§

Unknown(String)

未知错误

Implementations§

Source§

impl BaseError

Source

pub fn code(&self) -> i32

获取错误码

返回与错误类型对应的数字错误码,用于 API 响应

§错误码规范
  • 1xxxxx: 插件管理错误
  • 2xxxxx: 数据库错误
    • 21xxxx: Redis 错误(隶属数据库 2xxxxx 大类)
  • 3xxxxx: HTTP 客户端错误
  • 4xxxxx: Token 管理错误
  • 5xxxxx: 序列化错误
  • 6xxxxx: 字段验证错误
  • 7xxxxx: Action 系统错误
  • 9xxxxx: 通用错误
§返回
  • 错误码(非零整数)
§示例
ⓘ
use yang_base::error::BaseError;

let error = BaseError::FieldRequired("username".to_string());
assert_eq!(error.code(), 600006);
Source

pub fn code_str(&self) -> &'static str

返回错误码的 &'static str 形式,供 metrics label 使用(零分配、低基数)。

与 BaseError::code 一一对应:code_str() 是 code() 的字符串字面量版本, 专用于 metrics 的 label(label 必须是 &'static str,严禁 code().to_string() 造成每次派发堆分配 + 高基数)。新增变体时两者需同步维护,并由 test_code_str_matches_code 守护一致性。

Source

pub fn category(&self) -> ErrorCategory

引擎级错误分类(弹性重试与任意下游适配的共同基座)。

返回 ErrorCategory,是 is_retryable / is_client_error / is_server_error 的单一事实源。分类语义为引擎自有,与具体 HTTP status 映射无关——HTTP 映射属调用方传输层边界。

Transient 在 is_server_error 中视为服务端错误(但可重试), 在 is_client_error 中不视为客户端错误。Auth 和 NotFound 在 is_client_error 中视为客户端错误(认证/授权失败和资源不存在均归调用方过错)。

Source

pub fn sql_error_info(&self) -> Option<&SqlErrorInfo>

暴露包裹的 SQLSTATE 结构化信息(含约束/表/列/诊断)。

外键、NOT NULL、CHECK 等约束错误在映射时保留原始 DatabaseError, 调用方可据此分流,而无需解析本地化报文。

Source

pub fn sqlstate(&self) -> Option<&str>

原始 SQLSTATE 五字符码;无结构化数据库错误时返回 None。

Source

pub fn constraint(&self) -> Option<&str>

触发错误的约束名(如外键/唯一索引/CHECK 名称)。

Source

pub fn is_retryable(&self) -> bool

是否为可重试的瞬时错误。

包裹的 yang_db::DbError 以其自身 is_retryable() 为准:PostgreSQL 40001/40P01、08xxx、53xxx 可重试;55P03/57014/25P02 不可。 非数据库错误沿用 BaseError::category 的 Transient 语义。

Source

pub fn is_transaction_aborted(&self) -> bool

是否处于 PostgreSQL 的「事务已中止」状态(SQLSTATE 25P02)。

此时任何语句都会继续失败,必须先 ROLLBACK。

Source

pub fn is_timeout(&self) -> bool

是否为超时/取消类错误:57014(语句取消)或 55P03(锁不可用), 以及既有 HTTP 超时。

Source

pub fn is_client_error(&self) -> bool

是否为客户端过错(Client、Auth 或 NotFound 类)。

用于下游统一适配——客户端过错不可重试,调用方应修正请求而非重试。 注意 Transient 不在此列:虽然瞬时错误也可归「服务端」,但它不是 调用方过错,且可重试——is_server_error 已覆盖该语义。

Source

pub fn is_server_error(&self) -> bool

是否为服务端/基础设施错误(Server、Transient 或 Conflict)。

用于下游统一适配。Transient 在此视为服务端(可重试的服务端错误, 如连接超时 = HTTP 503 语义);Conflict 也计入(资源冲突 = HTTP 409, 但常由并发写引起而非纯调用方过错)。

Trait Implementations§

Source§

impl Debug for BaseError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for BaseError

Source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for BaseError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<DbError> for BaseError

从 yang_db::DbError 转换为 BaseError

按 DbError 变体分类映射到对应的 BaseError 变体:

  • 查询类 → DatabaseQueryFailed
  • 执行类 → DatabaseExecuteFailed(唯一键冲突例外,见下)
  • 事务类 → DatabaseTransactionFailed
  • 连接类 → DatabaseConnectionFailed(包装 DbError 保留错误链)
  • Redis 连接类 → RedisConnectionFailed
  • Redis 其他操作类 → RedisOperationFailed

唯一键冲突映射为 BaseError::ParamInvalid:它是可归因的输入问题 (自动派生的 source_key、系统生成的 token 都可能撞唯一索引), 落成 DatabaseExecuteFailed 会让控制台只能显示「数据库执行失败」, 运维看不出撞的是哪个键。

Source§

fn from(err: DbError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for BaseError

从 std::io::Error 转换为 BaseError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for BaseError

从 serde_json::Error 转换为 BaseError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for BaseError

Available on crate feature http only.

从 reqwest::Error 转换为 BaseError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for BaseError

Available on crate feature token only.

从 jsonwebtoken::errors::Error 转换为 BaseError

按 ErrorKind 分类映射:

  • ExpiredSignature → TokenExpired
  • InvalidToken / InvalidSignature → TokenVerifyFailed
  • 其他 → TokenParseFailed
Source§

fn from(err: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more