anyhow

The anyhow crate provides a rich error type with support for carrying additional contextual information, which can be used to provide a semantic trace of what the program was doing leading up to the error.

This can be combined with the convenience macros from thiserror to avoid writing out trait impls explicitly for custom error types.

  1. use anyhow::{bail, Context, Result};
  2. use std::fs;
  3. use std::io::Read;
  4. use thiserror::Error;
  5. #[derive(Clone, Debug, Eq, Error, PartialEq)]
  6. #[error("Found no username in {0}")]
  7. struct EmptyUsernameError(String);
  8. fn read_username(path: &str) -> Result<String> {
  9.     let mut username = String::with_capacity(100);
  10.     fs::File::open(path)
  11.         .with_context(|| format!("Failed to open {path}"))?
  12.         .read_to_string(&mut username)
  13.         .context("Failed to read")?;
  14.     if username.is_empty() {
  15.         bail!(EmptyUsernameError(path.to_string()));
  16.     }
  17.     Ok(username)
  18. }
  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 slide should take about 5 minutes.

  • 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.
  • anyhow::Result<V> is a type alias for Result<V, anyhow::Error>.
  • Functionality provided by anyhow::Error may be familiar to Go developers, as it provides similar behavior to the Go error type and Result<T, anyhow::Error> is much like a Go (T, error) (with the convention that only one element of the pair is meaningful).
  • anyhow::Context is a trait implemented for the standard Result and Option types. use anyhow::Context is necessary to enable .context() and .with_context() on those types.

More to Explore

  • anyhow::Error has support for downcasting, much like std::any::Any; the specific error type stored inside can be extracted for examination if desired with Error::downcast.