skip to Main Content

I am currently using the official mongodb driver for rust and while looking at error type for mongodb I came across this line in the mongodb::error::Error implementation:

#[error("Kind: {kind}, labels: {labels:?}")]

What is the meaning of this line? What functionality does it add to the struct?

the mongodb::error::Errorstruct is defined as follows:

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

Source : here

2

Answers


  1. That is the error message attribute from thiserror. They enable you to construct implementations of the std::error::Error trait with custom messages in an easier way that by hand. You can see further above the linked line that the Error derive macro was imported in line 11.

    The linked example applies the attribute macro on a struct type, but it can also be used on enum variants. Another example on the use of this derive macro can be seen from the documentation itself.

    use thiserror::Error;
    
    #[derive(Error, Debug)]
    pub enum DataStoreError {
        #[error("data store disconnected")]
        Disconnect(#[from] io::Error),
        #[error("the data for key `{0}` is not available")]
        Redaction(String),
        #[error("invalid header (expected {expected:?}, found {found:?})")]
        InvalidHeader {
            expected: String,
            found: String,
        },
        #[error("unknown data store error")]
        Unknown,
    }
    

    See also:

    Login or Signup to reply.
  2. The line #[error("Kind: {kind}, labels: {labels:?}")] is a parameter that influences the #[derive(Error)] one line above.

    It specifies how the error can be printed; to be specific, it implements Display for the struct.

    See this example:

    use thiserror::Error;
    use std::collections::HashSet;
    
    #[derive(Clone, Debug, Error)]
    #[error("Kind: {kind}, labels: {labels:?}")]
    #[non_exhaustive]
    pub struct Error {
        kind: String,
        labels: HashSet<String>,
    }
    
    fn main() {
        let my_error = Error {
            kind: "SpecialKind".to_string(),
            labels: HashSet::from([
                "xyz".to_string(),
                "aaa".to_string()
            ])
        };
        
        println!("{}", my_error);
    }
    
    Kind: SpecialKind, labels: {"xyz", "aaa"}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search