Deriving Error Enums

The thiserror crate is a popular way to create an error enum like we did on the previous page:

1. use std::{fs, io};
2. use std::io::Read;
3. use thiserror::Error;

5. #[derive(Debug, Error)]
6. enum ReadUsernameError {
7. #[error("Could not read: {0}")]
8. IoError(#[from] io::Error),
9. #[error("Found no username in {0}")]
10. EmptyUsername(String),
11. }

13. fn read_username(path: &str) -> Result<String, ReadUsernameError> {
14. let mut username = String::with_capacity(100);
15. fs::File::open(path)?.read_to_string(&mut username)?;
16. if username.is_empty() {
17. return Err(ReadUsernameError::EmptyUsername(String::from(path)));
18. }
19. Ok(username)
20. }

22. fn main() {
23. //fs::write("config.dat", "").unwrap();
24. match read_username("config.dat") {
25. Ok(username) => println!("Username: {username}"),
26. Err(err)     => println!("Error: {err}"),
27. }
28. }

thiserror’s derive macro automatically implements std::error::Error, and optionally Display (if the #[error(...)] attributes are provided) and From (if the #[from] attribute is added). It also works for structs.

It doesn’t affect your public API, which makes it good for libraries.