You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust MongoDB驱动中#[error(...)]注解的作用解析

关于mongodb::error::Error中#[error]属性的解析

你在查看Rust官方MongoDB驱动的mongodb::error::Error结构体时,看到的#[error("Kind: {kind}, labels: {labels:?}")]是基于thiserror crate的属性宏,具体含义和功能如下:

核心含义

这行代码为Error结构体定义了错误信息的格式化规则,同时配合#[derive(Error)]自动实现Rust标准库的相关trait。

具体功能

  • 生成Display trait实现:当你将错误实例转为字符串(比如println!("{}", err))时,会按照指定格式输出内容。其中{kind}会调用ErrorKind的Display格式输出,{labels:?}使用Debug格式输出私有的HashSet<String>类型的labels字段。
  • 自动实现Error trait:借助thiserror的#[derive(Error)],结合#[error]属性,无需手动编写代码就能让Error结构体满足标准库Error trait的要求,包括错误描述、根源错误关联等。
  • 配合错误链机制:结构体中#[source]标记的source字段,会和#[error]一起工作,让错误实例支持source()方法调用,方便追踪错误的根源。

附Error结构体定义:

use thiserror::Error;

#[derive(Clone, Debug, Error)]
#[error("Kind: {kind}, labels: {labels:?}")]
#[non_exhaustive]
pub struct Error {
    /// The type of error that occurred.
    pub kind: Box<ErrorKind>,
    labels: HashSet<String>,
    pub(crate) wire_version: Option<i32>,
    #[source]
    pub(crate) source: Option<Box<Error>>,
}

内容的提问来源于stack exchange,提问作者Diwas Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:18:14