Dynamic Error Types

Sometimes we want to allow any type of error to be returned without writing our own enum covering all the different possibilities. std::error::Error makes this easy.

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

6. #[derive(Clone, Debug, Eq, Error, PartialEq)]
7. #[error("Found no username in {0}")]
8. struct EmptyUsernameError(String);

10. fn read_username(path: &str) -> Result<String, Box<dyn Error>> {
11. let mut username = String::with_capacity(100);
12. File::open(path)?.read_to_string(&mut username)?;
13. if username.is_empty() {
14. return Err(EmptyUsernameError(String::from(path)).into());
15. }
16. Ok(username)
17. }

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

This saves on code, but gives up the ability to cleanly handle different error cases differently in the program. As such it’s generally not a good idea to use Box<dyn Error> in the public API of a library, but it can be a good option in a program where you just want to display the error message somewhere.