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::Error
struct 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
That is the error message attribute from
thiserror
. They enable you to construct implementations of thestd::error::Error
trait with custom messages in an easier way that by hand. You can see further above the linked line that theError
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.
See also:
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: