Sub topic 6
Application errors with anyhow::Result
This chapter assumes you know Result, the ? operator, enums, and traits. You should also have seen a hand-written error type and the thiserror derive from earlier chapters. Here you will meet anyhow, the crate most Rust binaries use for error handling.
The problem anyhow solves
A typed error enum is the right tool when callers need to react to specific failures. In an application's own code, though, nobody downstream matches on your errors. You usually want to propagate a failure to main, print it, and exit.
Without anyhow, one function that reads a file and parses a number has two different error types: std::io::Error and ParseIntError. You would have to write a combined enum with From impls just to use ? on both. That is a lot of code for an error nobody inspects.
What anyhow::Error is
anyhow::Error is a single error type that can hold any error implementing std::error::Error + Send + Sync + 'static. It stores the error on the heap, so the type stays one pointer wide. anyhow::Result<T> is an alias for Result<T, anyhow::Error>.
Because anyhow::Error implements From for every such error type, ? converts automatically.
Add the crate with Cargo:
cargo add anyhowHere is a function that mixes two error types and needs no custom enum:
use anyhow::Result;
use std::fs;
fn load_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)?; // io::Error becomes anyhow::Error
let port = text.trim().parse::<u16>()?; // ParseIntError becomes anyhow::Error
Ok(port)
}
fn main() -> Result<()> {
let port = load_port("port.txt")?;
println!("listening on {port}");
Ok(())
}When main returns Err, Rust prints the error using its Debug format and exits with a non-zero status code. For anyhow::Error, the Debug output is a readable report. It shows the message, followed by a "Caused by" list if the error has sources.
If port.txt does not exist, the output looks like this:
Error: No such file or directory (os error 2)That message does not say which file was missing. The next chapter fixes this with context.
How the conversion flows
The diagram shows how two different error types end up as one.
What you give up
anyhow::Error erases the concrete type. A caller of load_port cannot write match err { ... } on variants, because there are none. This is why anyhow suits application code and not public library APIs. A later chapter covers that choice in detail, and another shows how to recover a concrete type with downcasting.
You also cannot implement std::error::Error for anyhow::Error itself. It deliberately omits that impl so that the blanket From<E> conversion does not conflict with the standard library's From<T> for T. If you need to pass it to an API that requires E: std::error::Error, call .into_boxed_dyn_error(), or convert it with Box::<dyn std::error::Error + Send + Sync>::from(err).
Common errors
- Using
anyhow::Resultinmainbut forgetting the import. The standardResulttakes two type parameters. Writeuse anyhow::Result;or spell outanyhow::Result<()>. - Returning a
Stringas an error with?.Stringdoes not implementstd::error::Error, soErr("bad".to_string())?fails to compile. Use theanyhow!macro, covered later. - Using a non-
Senderror. An error type holding anRcwill not convert, becauseanyhow::ErrorrequiresSend + Sync.
Exercises
Exercise
A function returns anyhow::Result<u16>. Inside it you call std::fs::read_to_string(path)? and s.parse::<u16>()?. Why does the compiler accept both lines even though the two errors have different types?
Show answer
anyhow::Error implements From<E> for any E that implements std::error::Error + Send + Sync + 'static. io::Error and ParseIntError both qualify, so ? converts each one into anyhow::Error automatically.
Exercise
Why is anyhow::Error a poor return type for a function in a public library crate?
Show answer
It erases the concrete error type, so callers cannot match on specific variants to decide how to react. A library should return a typed error, such as one defined with thiserror.