Sub topic 12
Box<dyn Error> for quick, flexible error handling
This chapter assumes you know Result<T, E>, the ? operator, and how a custom error type implements Display, Error, and From. You should also know what a trait is at a conceptual level.
The problem with many error types
A function that parses a number and reads a file can fail in two different ways. Those failures have two different types: ParseIntError and std::io::Error. A return type of Result<T, E> allows only one E. A custom enum with a From impl for each source solves this, but it takes boilerplate. For a small tool or a prototype, that cost is often not worth paying.
The catch-all type
Box<dyn Error> is a heap-allocated trait object. It can hold any value whose type implements std::error::Error. Because the standard library provides impl<E: Error> From<E> for Box<dyn Error>, the ? operator converts any error into the box automatically.
use std::error::Error;
use std::fs;
fn read_port(path: &str) -> Result<u16, Box<dyn Error>> {
let text = fs::read_to_string(path)?;
let port = text.trim().parse::<u16>()?;
Ok(port)
}
fn main() {
match read_port("port.txt") {
Ok(port) => println!("port {port}"),
Err(e) => println!("error: {e}"),
}
}The first ? can return an io::Error. The second can return a ParseIntError. Both become Box<dyn Error> without any From code on your side.
Creating errors from strings
You can also build an error from a message. A &str or String converts into Box<dyn Error> with .into() or ?.
use std::error::Error;
fn check_port(port: u16) -> Result<u16, Box<dyn Error>> {
if port < 1024 {
return Err("port must be 1024 or higher".into());
}
Ok(port)
}
fn main() -> Result<(), Box<dyn Error>> {
println!("{}", check_port(8080)?);
println!("{}", check_port(80)?);
Ok(())
}Because main returns the error, Rust prints it in Debug form and exits with a nonzero status.
How it fits together
Trade-offs
The box erases the concrete type. The caller can no longer match on variants to decide what to do. You can try to recover the type with downcast_ref, but this is awkward and easy to get wrong.
| Situation | Better choice |
|---|---|
| Small binary, script, or prototype | `Box<dyn Error>` |
| Library with a public API | A custom error enum |
| Callers must react to specific failures | A custom error enum |
The box also costs a heap allocation when an error occurs. That is rarely a problem, because errors are the uncommon path.
Exercise
Why does ? work on both a ParseIntError and an io::Error inside a function returning Result<T, Box<dyn Error>>, and what do you give up compared with a custom error enum?
Show answer
The standard library implements From<E> for Box<dyn Error> for every E that implements Error, so ? converts each error into the box automatically. You give up the concrete type: callers cannot match on specific variants, and can only inspect the error through Display, Debug, or downcast_ref.