Sub topic 3
Box<dyn Error> for Quick, Flexible Error Handling
Assume you know Result, Option, match, traits, and ownership. This chapter focuses on choosing an error type when a function can fail in several unrelated ways.
Box<dyn Error> for Quick, Flexible Error Handling
Box<dyn Error> is a heap-allocated value containing any type that implements the standard Error trait. It lets one function return errors from different libraries without defining an enum for every case.
use std::error::Error;
use std::fs;
fn load_count() -> Result<u32, Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
let count = text.trim().parse::<u32>()?;
Ok(count)
}The ? operator converts both io::Error and ParseIntError into the boxed error type. This is convenient for small programs, examples, and application boundaries. A custom enum is usually better for libraries because callers can match specific error cases.
Returning `Result` from `main`
main may return a Result. Returning Ok(()) means success. Returning Err prints the error and exits with a failure status.
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("count.txt")?;
let count: u32 = text.trim().parse()?;
println!("count = {count}");
Ok(())
}Common Limits of `?`
The enclosing function must return a compatible type. You cannot use ? in a function returning u32, because failure has nowhere to go. Also, ? does not automatically convert an Option<T> into a Result<T, E>, or choose an arbitrary error message. Use ok_or_else when crossing that boundary.
Collecting Results
An iterator of Result<T, E> can be collected into Result<Vec<T>, E>. Collection stops at the first error.
fn parse_all(items: &[&str]) -> Result<Vec<i32>, std::num::ParseIntError> {
items.iter().map(|item| item.parse::<i32>()).collect()
}Reducing Boilerplate
The thiserror crate derives Display and Error for a custom enum. It suits libraries that need stable, matchable errors. The anyhow crate provides a convenient application error type with context and reporting. Choose thiserror for an API contract and anyhow for application-level propagation.
Exercise
Why does ? work in load_count but not in a function returning u32?
Show answer
load_count returns a compatible Result, so failure can be returned early. A u32 return type has no error channel.