thiserror is a Rust library crate for defining custom error types with less repetitive code. Its main convenience is the derive macro thiserror::Error, which implements std::error::Error for your type. section 17.5 section 17.5.2
A typical custom error enum uses attributes to describe messages and conversions:
- Add #[derive(Error, Debug)] to the enum. section 17.5.2
- Put #[error("...")] above each variant to generate its Display message; the format follows format! syntax. section 17.5.2
- Put #[from] on an error field to generate a From implementation, allowing the ? operator to convert that error into the custom enum. section 17.5.2
- Use the custom enum when a library needs a proper, discoverable error type rather than only one general-purpose error value. section 17.5 section 17.8
One error type for several failures
An enum can represent sending, UTF-8, parsing, color, and other failures. With #[from] on Utf8Error and ParseIntError, parse_then_send can use ? while still returning Result<(), SystemError>. Display produces messages such as “Couldn't turn into an i32: invalid digit found in string”; Debug does not show these added messages.
#[derive(Error, Debug)] #1
enum SystemError {
#[error("Couldn't send: {0}")] #2
SendError(String),
#[error("Couldn't parse into a str: {0}")] #3
StringFromUtf8Error(#[from] Utf8Error),
#[error("Couldn't turn into an i32: {0}")]
ParseI32Error(#[from] ParseIntError),
#[error("Wrong color: Red {0} Green {1} Blue {2}")] #4
ColorError(u8, u8, u8),
#[error("Something happened")]
OtherError,
}
Inspect the annotated SystemError enum to see how derive, error messages, source error fields, and numeric formatting fit together. section 17.5.2
