Member-only story

Rust must-know libraries thiserror and anyhow

thiserror

Beck Moulton
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 :: errortrait... 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 the std :: error :: Errortrait.
  • #[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 Displayimplementation is automatically generated.
  • #[error ("{var}") ]corresponds to write !("{}", self.var)
  • #[error ("{0}") ]corresponds to write !("{}", self.0)
  • Formatted versions are also supported, such as #[error ("{var :?}")]
  • #[From]: Automatically implements the Fromtrait, allowing conversions from other error types.

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet