Sub topic 12
Box<dyn Error> for quick, flexible error handling
This chapter assumes you know how ? works, how From conversions are used for errors, and what a trait is at a conceptual level. The previous chapters showed a custom error enum with a From implementation for each error source. That approach is precise but takes a lot of code. When a function can fail in several unrelated ways, Box<dyn Error> gives you one return type that holds any of them.
What the type means
dyn Error is a trait object. It stands for "some value whose concrete type is unknown here, but which implements the Error trait". Trait objects have no fixed size, so they must sit behind a pointer. Box provides that pointer and puts the error on the heap.
So Result<T, Box<dyn Error>> means: either a T, or a heap-allocated error of any type that implements Error. The caller sees one type, whatever went wrong inside.
The standard library supplies the conversions that make this convenient:
impl<E: Error> From<E> for Box<dyn Error>lets?convert any error type into the box.impl From<&str> for Box<dyn Error>andimpl From<String> for Box<dyn Error>let you build an ad hoc error from text.
A first example
use std::error::Error;
fn parse_sum(input: &str) -> Result<i32, Box<dyn Error>> {
let mut total = 0;
for part in input.split(',') {
total += part.trim().parse::<i32>()?;
}
Ok(total)
}
fn main() {
println!("{:?}", parse_sum("1, 2, 3"));
println!("{:?}", parse_sum("1, x"));
}This prints Ok(6) and then Err(ParseIntError { kind: InvalidDigit }). The ? after parse produces a ParseIntError. Because the function returns Box<dyn Error>, ? calls From::from and boxes it. You wrote no enum and no impl From.
Mixing error types in one function
The benefit shows when one function has several failure sources:
use std::error::Error;
use std::fs;
fn load_port(path: &str) -> Result<u16, Box<dyn Error>> {
let text = fs::read_to_string(path)?;
let line = text.lines().next().ok_or("file is empty")?;
let port = line.trim().parse::<u16>()?;
if port < 1024 {
return Err(format!("port {port} is reserved").into());
}
Ok(port)
}
fn main() {
match load_port("port.txt") {
Ok(port) => println!("port {port}"),
Err(e) => eprintln!("error: {e}"),
}
}Four different failures share one return type:
read_to_stringfails withstd::io::Error.ok_or("file is empty")makes aResult<&str, &str>. The?converts the&strinto a boxed error.parsefails withParseIntError.- The reserved-port check builds a
Stringand calls.into()to box it.
When port.txt is missing, the program prints error: No such file or directory (os error 2). The {e} format uses Display, which every Error type must implement. The {:?} format uses Debug, which every Error type must also implement.
Returning it from main
main can return Result<(), Box<dyn Error>>, which pairs well with this type. Every ? in main then works regardless of which error occurs.
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let n: i32 = "42".parse()?;
println!("n = {n}");
let m: i32 = "4x2".parse()?;
println!("m = {m}");
Ok(())
}The first line prints n = 42. The second parse fails, so the process prints Error: ParseIntError { kind: InvalidDigit } to standard error and exits with a nonzero status. Rust prints the Debug form here, not Display. If you want friendlier text, catch the error in main yourself with match and print {e}.
Recovering the concrete type
A boxed error hides its type, but you can ask for it back. downcast_ref returns Some(&T) if the box holds a T, and None otherwise.
use std::error::Error;
use std::num::ParseIntError;
fn run(s: &str) -> Result<u16, Box<dyn Error>> {
Ok(s.parse::<u16>()?)
}
fn main() {
let err = run("abc").unwrap_err();
if let Some(e) = err.downcast_ref::<ParseIntError>() {
println!("parse problem: {e}");
} else {
println!("other problem: {err}");
}
}This prints parse problem: invalid digit found in string. Downcasting works, but it is a runtime check. The compiler cannot tell you which cases you forgot, as it can with match on an enum. If you find yourself downcasting often, switch to a custom enum.
Walking the cause chain
The Error trait has a source method that returns the underlying cause, if any. A boxed error keeps this chain, so you can print a full report:
use std::error::Error;
fn report(err: &dyn Error) {
eprintln!("error: {err}");
let mut current = err.source();
while let Some(cause) = current {
eprintln!(" caused by: {cause}");
current = cause.source();
}
}
fn main() {
let err: Box<dyn Error> = "no config found".into();
report(err.as_ref());
}A string-based error has no source, so this prints only error: no config found. Errors that wrap another error, such as a custom type that overrides source, print each level.
Gotchas
Box<dyn Error> does not implement Error. The blanket From<E: Error> conversion would overlap with the standard From<T> for T if it did. A function with a bound like fn log<E: Error>(e: E) therefore rejects a Box<dyn Error>. Take &dyn Error instead and pass err.as_ref(), as the example above does.
Threads need more bounds. Sending an error to another thread requires Send. The type Box<dyn Error + Send + Sync> has that guarantee, and the &str and String conversions still work for it. Many async libraries and thread spawners require this form, so it is a common default in application code.
The allocation happens only on failure. ? boxes the error on the failure path only. The success path costs nothing extra. For most programs this is irrelevant, but a hot loop that fails often may notice.
Callers lose precision. A signature of Result<T, Box<dyn Error>> tells the caller nothing about what can go wrong. They cannot write an exhaustive match, and the documentation must carry the information instead.
Choosing between a box and an enum
| Situation | Better choice |
|---|---|
| Binary, script, prototype, or `main` | `Box<dyn Error>` |
| Library other code depends on | Custom error enum |
| Callers must react differently to each failure | Custom error enum |
| Many unrelated error sources, no recovery | `Box<dyn Error>` |
| You need to avoid heap allocation | Custom error enum |
A common path is to start with Box<dyn Error> while exploring, then replace it with an enum at the point where callers need to tell failures apart. Because ? handles the conversion, the function bodies rarely change. Only the signature and the type definition do.
Exercise
The function below fails to compile. What is wrong, and how do you fix it using Box<dyn Error>? fn readcount(text: Option<&str>) -> Result<u32, std::num::ParseIntError> { let t = text.okor("missing value")?; Ok(t.trim().parse::<u32>()?) }
Show answer
The ? after ok_or("missing value") produces a &str error, but the return type only accepts ParseIntError, and no From<&str> conversion to that type exists. Change the return type to Result<u32, Box<dyn std::error::Error>>. Then ? converts both the &str and the ParseIntError into the box, and the function body stays the same.