-
Book Overview & Buying
-
Table Of Contents
The Rust Programming Handbook
By :
Manually implementing the Display and Error traits for every custom error type can become repetitive. Fortunately, the Rust community has created excellent crates (libraries) to streamline this process. The two most popular crates for error handling are thiserror and anyhow.
The thiserror crate drastically reduces the boilerplate code needed for custom errors. By using the #[derive(Error)] macro and attributes such as #[error("...")] and #[from], you can automatically generate Display and Error trait implementations, making your error types both ergonomic and powerful.
The #[from] attribute is particularly useful as it generates From trait implementations, allowing the ? operator to automatically convert source errors (such as io::Error or ParseIntError) into the appropriate variant of your custom error enum.
Let’s see a practical example with a main function that handles the various...