Skip to main content

DbError

Enum DbError 

Source
#[non_exhaustive]
pub enum DbError {
Show 25 variants QueryError(String), ConnectionError(String), ConnectionRefused(String), ConnectionTimeout(String), PoolError(PoolError), CacheError(CacheError), TxError(TxError), MigrationError(String), Unsupported(String), ConfigError(String), SerdeError(String), NotFound(String), AlreadyExists(String), ConstraintViolation(String), UniqueViolation(String), ForeignKeyViolation(String), NullValue(String), InvalidInput(String), Internal(String), IoError(String), Hook(String), TenantError(String), Validation(String), Contextual { source: Box<DbError>, context: ErrorContext, }, Extension { ext_name: &'static str, message: String, },
}
Expand description

数据库错误类型

P1-3 统一错误类型:本类型作为 sz-orm 全工作空间的统一错误包装层。 各扩展包(sz-orm-auth/storage/vector 等)的独立错误类型应实现 From<ExtError> for DbError, 调用方可通过 Result<T, DbError> 统一处理核心与扩展错误。

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.
§

QueryError(String)

查询执行失败

§

ConnectionError(String)

连接失败

§

ConnectionRefused(String)

连接被拒绝

§

ConnectionTimeout(String)

连接超时

§

PoolError(PoolError)

连接池错误

§

CacheError(CacheError)

缓存错误

§

TxError(TxError)

事务错误

§

MigrationError(String)

迁移错误

§

Unsupported(String)

方言不支持

§

ConfigError(String)

配置错误

§

SerdeError(String)

序列化/反序列化错误

§

NotFound(String)

未找到

§

AlreadyExists(String)

已存在

§

ConstraintViolation(String)

约束冲突(通用回退,无法确定具体类型时使用)

§

UniqueViolation(String)

唯一约束冲突(UNIQUE constraint)

§

ForeignKeyViolation(String)

外键约束冲突(FOREIGN KEY constraint)

§

NullValue(String)

非空字段出现 null 值

§

InvalidInput(String)

输入非法

§

Internal(String)

内部错误

§

IoError(String)

IO 错误

§

Hook(String)

钩子执行失败

§

TenantError(String)

多租户错误(如租户 ID 缺失、跨租户访问)

§

Validation(String)

数据验证失败(业务规则校验未通过,由 before_validate 钩子触发)

§

Contextual

#6 修复:带上下文链的错误

包装原始错误 + 上下文链,用于在错误传播路径上附加调用方上下文。 通过 DbError::with_context("operation") 创建。

Fields

§source: Box<DbError>

原始错误(Box 避免递归类型大小爆炸)

§context: ErrorContext

上下文链头节点

§

Extension

P1-3:扩展包错误统一包装

用于将 sz-orm-auth/storage/vector/postgis/search/timeseries/mqtt/mig 等 扩展包的独立错误类型统一包装为 DbError,实现全工作空间错误类型统一。

  • ext_name: 扩展包名(如 “auth”, “storage”)
  • message: 原始错误的 Debug 描述

Fields

§ext_name: &'static str

扩展包名(如 “auth”, “storage”, “vector”)

§message: String

原始错误消息

Implementations§

Source§

impl DbError

Source

pub fn query(s: impl Into<String>) -> Self

新建查询错误

Source

pub fn connection(s: impl Into<String>) -> Self

新建连接错误

Source

pub fn not_found(s: impl Into<String>) -> Self

新建未找到错误

Source

pub fn with_context(self, context: impl Into<String>) -> Self

#6 修复:附加错误上下文(消费 self,返回带上下文的新错误)

用于在错误传播路径上附加调用方上下文,形成 error.with_context("operation") 链式调用。多次调用会形成上下文链表。

§示例
fn fetch_user(id: i64) -> Result<User, DbError> {
    db.query("SELECT * FROM users WHERE id = ?", &[id.into()])
        .await
        .map_err(|e| e.with_context(format!("fetching user id={}", id)))?;
    // ...
}
Source

pub fn with_context_in_span( self, context: impl Into<String>, span: impl Into<String>, ) -> Self

#6 修复:附加错误上下文(含 tracing span 名)

Source

pub fn context(&self) -> Option<&ErrorContext>

#6 修复:获取错误上下文链(None 表示无附加上下文)

Source

pub fn format_context_chain(&self) -> String

#6 修复:格式化错误上下文链为多行字符串

Source

pub fn root_cause(&self) -> &DbError

#6 修复:剥离上下文链,返回原始错误引用

Source

pub fn is_retryable(&self) -> bool

该错误是否可重试

Source

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

获取错误码(用于日志/监控)

Source

pub fn http_status(&self) -> u16

映射到 HTTP 状态码(RFC 7231)

用于在 HTTP 服务(如 axum/actix)中根据数据库错误返回合适的 HTTP 状态码。

  • 400 Bad Request:非法输入、参数校验失败、配置错误
  • 404 Not Found:资源未找到
  • 409 Conflict:资源已存在、约束冲突(唯一/外键/非空/通用)
  • 422 Unprocessable Entity:序列化/反序列化错误
  • 500 Internal Server Error:查询失败、内部错误、钩子失败、迁移失败、IO 错误、事务错误、租户错误
  • 501 Not Implemented:方言/功能不支持
  • 502 Bad Gateway:连接错误、连接被拒绝
  • 503 Service Unavailable:连接池耗尽/关闭、缓存错误
  • 504 Gateway Timeout:连接超时、连接池获取超时
Source

pub fn grpc_status_code(&self) -> u32

映射到 gRPC 状态码

用于在 gRPC 服务(tonic)中根据数据库错误返回合适的 gRPC 状态码。 参考:https://grpc.io/docs/guides/status-codes/

  • 2 UNKNOWN:查询失败、内部错误、钩子失败、迁移失败、IO 错误
  • 3 INVALID_ARGUMENT:非法输入、参数校验失败、配置错误
  • 4 DEADLINE_EXCEEDED:连接超时、连接池获取超时
  • 5 NOT_FOUND:资源未找到
  • 6 ALREADY_EXISTS:资源已存在、唯一约束冲突
  • 7 PERMISSION_DENIED:租户错误(跨租户访问)
  • 8 RESOURCE_EXHAUSTED:连接池耗尽/关闭、缓存错误
  • 9 FAILED_PRECONDITION:约束冲突(通用/外键/非空)、事务错误
  • 12 UNIMPLEMENTED:方言/功能不支持
  • 13 INTERNAL:序列化/反序列化错误
  • 14 UNAVAILABLE:连接错误、连接被拒绝、连接创建失败

Trait Implementations§

Source§

impl Debug for DbError

Source§

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

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

impl Display for DbError

Source§

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

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

impl Error for DbError

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<Error> for DbError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for DbError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<FromUtf8Error> for DbError

Source§

fn from(err: FromUtf8Error) -> Self

Converts to this type from the input type.
Source§

impl<T> From<PoisonError<T>> for DbError

Source§

fn from(err: PoisonError<T>) -> Self

Converts to this type from the input type.
Source§

impl From<TryFromIntError> for DbError

Source§

fn from(err: TryFromIntError) -> 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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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<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