Sub topic 10
Box<dyn Error> for quick, flexible error handling
This chapter assumes you can write functions that return Result, use ? to propagate errors, and read a basic trait implementation. You should also know that ? converts the error with From before it returns. The previous chapter showed how to build a custom error enum. This chapter shows the shortcut: a single error type that accepts almost any error.
The problem: many error types in one function
A function that reads a file and parses its contents can fail in two ways. fs::read_to_string returns io::Error, and str::parse::<u16> returns ParseIntError. A function has one return type, so Result<u16, io::Error> rejects the parse error and Result<u16, ParseIntError> rejects the I/O error.
A custom enum solves this, but it costs a type, a Display impl, an Error impl, and one From impl per source error. When you write a small tool, a prototype, or an application's top level, that cost may not be worth it.
Box<dyn Error> is the alternative. It is a heap-allocated value of any type that implements the std::error::Error trait. The caller sees one error type, and each error keeps its own concrete type underneath.
A first example
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 port = text.trim().parse::<u16>()?;
if port < 1024 {
return Err(format!("port {port} is reserved").into());
}
Ok(port)
}
fn main() {
match load_port("port.txt") {
Ok(p) => println!("port = {p}"),
Err(e) => eprintln!("error: {e}"),
}
}The function has three different failure sources:
- The first
?can return anio::Error. - The second
?can return aParseIntError. - The
Err(...)line returns a plain message built withformat!.
All three end up as Box<dyn Error>, and none needed a custom From impl.
Why the conversion works
The standard library contains this blanket implementation, shown here in simplified form:
impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a>Read it as "any type E that implements Error can convert into a Box<dyn Error>". The ? operator calls From::from on the error before it returns, so any Error type passes through. Chapter "Converting errors automatically with From" covered that mechanism. Here the compiler already has an impl for every error type.
Two more impls cover plain text:
From<&str> for Box<dyn Error>From<String> for Box<dyn Error>
These let you write Err("something went wrong".into()) and Err(format!("bad value {n}").into()). The text is wrapped in a private error type that implements Error and Display. You can also write Err("message")?, which applies From through ?.
What the box holds
dyn Error is a trait object. It is a value whose concrete type is known only at runtime, reached through a pointer plus a table of methods (a vtable). Box supplies the pointer and the heap allocation. You can call these Error methods on the box:
Displayformatting with{e}, which gives the message.Debugformatting with{e:?}, which shows the underlying type's debug form.source(), which returns the underlying cause, if any.
The cost is one heap allocation per error and a virtual call when you print it. Errors are rare and usually end in a log line, so this seldom matters.
Recovering the concrete type
The concrete type is hidden but not lost. downcast_ref checks at runtime whether the box holds a given type:
use std::error::Error;
use std::io;
fn run() -> Result<(), Box<dyn Error>> {
let _text = std::fs::read_to_string("missing.txt")?;
Ok(())
}
fn main() {
if let Err(e) = run() {
if let Some(io_err) = e.downcast_ref::<io::Error>() {
println!("io problem, kind = {:?}", io_err.kind());
} else {
println!("other error: {e}");
}
}
}downcast_ref::<T>() returns Some(&T) when the box holds a T and None otherwise. downcast::<T>() consumes the box and returns Result<Box<T>, Box<dyn Error>>. Use these sparingly. If callers must branch on the failure kind, an enum is a better fit, because match checks that you handled every case and a chain of downcast_ref calls does not.
Walking the source chain
Errors can wrap other errors. Error::source exposes the wrapped cause. A reporting function can print the whole chain:
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 run() -> Result<(), Box<dyn Error>> {
let _n: i32 = "abc".parse()?;
Ok(())
}
fn main() {
if let Err(e) = run() {
report(e.as_ref());
}
}as_ref() turns the Box<dyn Error> into a &dyn Error. A ParseIntError has no source, so only one line prints here. Errors you wrap yourself, such as the ConfigError::BadNumber variant from the previous chapter, would print a second line.
Adding Send and Sync
The plain Box<dyn Error> does not promise that the error is safe to move to another thread. If you return errors from thread::spawn or from async tasks, you usually need Box<dyn Error + Send + Sync>. A type alias keeps signatures short:
use std::error::Error;
use std::thread;
type BoxError = Box<dyn Error + Send + Sync>;
fn work() -> Result<u32, BoxError> {
let n: u32 = "42".parse()?;
Ok(n * 2)
}
fn main() -> Result<(), BoxError> {
let handle = thread::spawn(work);
let value = handle.join().map_err(|_| "worker panicked")??;
println!("{value}");
Ok(())
}The same From impls exist for the Send + Sync form, so ? and .into() work the same way. The only errors that fail to convert are those that are not Send or not Sync, such as an error that holds an Rc. The compiler reports that mismatch at the ?.
A library should pick one form and keep it. Changing Box<dyn Error> to Box<dyn Error + Send + Sync> later is a breaking change for callers who name the type.
Choosing between Box<dyn Error> and a custom enum
| Question | Box<dyn Error> | Custom enum |
|---|---|---|
| Setup cost | One line in the signature | Type, Display, Error, and From impls |
| Callers can match on failure kinds | No, only downcasting | Yes, with exhaustive `match` |
| New error sources | Work automatically | Need a new variant and From impl |
| Allocation | One heap allocation per error | None beyond the variants' own data |
| Stable public API | Weak, since any error can appear | Strong, the variants are the contract |
| Best place | `main`, scripts, prototypes, tests | Library boundaries, code that reacts to specific errors |
A common pattern is a custom enum inside a library and Box<dyn Error> in the binary that calls it. The library's enum implements Error, so it converts into the box with no extra code.
Gotchas
- The box does not implement Error.
Box<dyn Error>itself does not implementError. If it did, the blanketFrom<E>impl would overlap with the standardFrom<T> for T. The practical effect is that you cannot pass aBox<dyn Error>to code that requiresE: Error. Usee.as_ref()to get a&dyn Error, which works where a&dyn Erroris accepted. - A custom type needs both traits. To convert your own type into the box, implement
Error, which also requiresDebugandDisplay. Without those,?fails with "the trait bound ...Erroris not satisfied". - Wrong return type shows up late. If you write
Result<T, Box<dyn Error>>but a helper returnsResult<T, String>,?fails, becauseStringdoes not implementError. Convert it with.map_err(|s| s.into()), or make the helper return&strorStringthroughErr(s.into()). - Inference needs a target type.
let e = "oops".into();has no way to pickBox<dyn Error>. Writelet e: Box<dyn Error> = "oops".into();. InsideErr(...)in a function with a known return type, inference works. - Context is lost. A bare
?on a file error says only "No such file or directory (os error 2)". It does not say which file. Add context withmap_err, for example.map_err(|e| format!("reading {path}: {e}"))?. Theanyhowcrate, covered later, automates this.
Putting it together
This program mixes all the sources we have seen. It reads a config file, parses a number, and rejects out-of-range values with a message:
use std::error::Error;
use std::fs;
fn read_limit(path: &str) -> Result<u32, Box<dyn Error>> {
let text = fs::read_to_string(path)
.map_err(|e| format!("cannot read {path}: {e}"))?;
let limit: u32 = text.trim().parse()?;
if limit == 0 {
return Err("limit must be greater than zero".into());
}
Ok(limit)
}
fn main() -> Result<(), Box<dyn Error>> {
let limit = read_limit("limit.txt")?;
println!("limit = {limit}");
Ok(())
}If limit.txt is missing, the process prints Error: "cannot read limit.txt: No such file or directory (os error 2)" and exits with status 1. The quotes appear because main prints the error with Debug, and a message built from a String is shown as a quoted string. An error with a derived Debug, such as ParseIntError, prints as ParseIntError { kind: InvalidDigit }.
Exercise
A function returns Result<(), Box<dyn Error>>. Its body calls File::open(path)?, then calls helper()? where helper returns Result<(), String>. The code does not compile. Why does the String call fail, and give two ways to fix it.
Show answer
? needs Box<dyn Error>: From<String>. That impl exists, so the conversion of a plain String is not the issue. The issue is in the premise: From<String> for Box<dyn Error> does exist, so this code compiles as written. The common failing case is a Result<(), String> where the function's error type is a custom type or Box<dyn Error + Send + Sync> holding a non-Send error. Verify by reading the compiler message. When a real mismatch occurs because a helper's error type does not implement Error (for example a unit-like or tuple type), fix it by either (1) converting at the call site with helper().map_err(|e| format!("helper failed: {e:?}"))?, or (2) changing the helper to return Result<(), Box<dyn Error>> or a type that implements Error.
Exercise
Write a function sum_file(path: &str) -> Result<i64, Box<dyn Error>> that reads a file with one integer per line and returns their sum. Return an error built from a string if the file is empty. Which three kinds of failure can it report?
Show answer
Use let text = fs::read_to_string(path)?;, then let mut total = 0i64; let mut count = 0;, and for each line in text.lines() do total += line.trim().parse::<i64>()?; count += 1;. After the loop, if count == 0 { return Err("file is empty".into()); } and Ok(total). The three failures are an io::Error from reading the file, a ParseIntError from a bad line, and the string error for an empty file.