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};
  4. fn read_username(path: &str) -> Result<String> {
  5. let mut username = String::with_capacity(100);
  6. fs::File::open(path)
  7. .context(format!("Failed to open {path}"))?
  8. .read_to_string(&mut username)
  9. .context("Failed to read")?;
  10. if username.is_empty() {
  11. bail!("Found no username in {path}");
  12. }
  13. Ok(username)
  14. }
  15. fn main() {
  16. //fs::write("config.dat", "").unwrap();
  17. match read_username("config.dat") {
  18. Ok(username) => println!("Username: {username}"),
  19. Err(err) => println!("Error: {err:?}"),
  20. }
  21. }
  • anyhow::Result<V> is a type alias for Result<V, anyhow::Error>.
  • anyhow::Error is essentially a wrapper around Box<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.