Adding Context to Errors
The widely used anyhow crate can help you add contextual information to your errors and allows you to have fewer custom error types:
1. use std::{fs, io};
2. use std::io::Read;
3. use anyhow::{Context, Result, bail};
5. fn read_username(path: &str) -> Result<String> {
6. let mut username = String::with_capacity(100);
7. fs::File::open(path)
8. .context(format!("Failed to open {path}"))?
9. .read_to_string(&mut username)
10. .context("Failed to read")?;
11. if username.is_empty() {
12. bail!("Found no username in {path}");
13. }
14. Ok(username)
15. }
17. fn main() {
18. //fs::write("config.dat", "").unwrap();
19. match read_username("config.dat") {
20. Ok(username) => println!("Username: {username}"),
21. Err(err) => println!("Error: {err:?}"),
22. }
23. }
anyhow::Result<V>is a type alias forResult<V, anyhow::Error>.anyhow::Erroris essentially a wrapper aroundBox<dyn Error>. As such it’s again generally not a good choice for the public API of a library, but is widely used in applications.- Actual error type inside of it can be extracted for examination if necessary.
- Functionality provided by
anyhow::Result<T>may be familiar to Go developers, as it provides similar usage patterns and ergonomics to(T, error)from Go.
