Member-only story
Rust must-know libraries thiserror and anyhow
thiserror
4 min readAug 28, 2024
Thiserror is a library for simplifying custom error type definitions, which provides a convenient derived macro for the standard library std :: error :: error
trait... Here are the main features and usage of thiserror.
To use thiserror, first add a dependency in Cargo.toml:
[dependencies] thiserror = "1.0"
Then, you can define an error type like this:
use thiserror::Error;#[derive(Error, Debug)]
pub enum MyError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error), #[error("Parse error: {0}")]
Parse(#[from] std::num::ParseIntError), #[error("Custom error: {msg}")]
Custom { msg: String },
}
#[derive (Error) ]
: This derived macro automatically implements thestd :: error :: Error
trait.#[error ("...") ]
: Defines the format of the error message. Fields can be referenced using placeholders.- If you provide a #[error (“…”) ] message on each variant of a struct or enumeration, a
Display
implementation is automatically generated. #[error ("{var}") ]
corresponds towrite !("{}", self.var)
#[error ("{0}") ]
corresponds towrite !("{}", self.0)
- Formatted versions are also supported, such as
#[error ("{var :?}")]
#[From]
: Automatically implements theFrom
trait, allowing conversions from other error types.