Sub topic 12
Returning Mixed Errors with Box<dyn Error>
This chapter assumes you know Result, the ? operator, and how to read lines from a locked stdin handle. You should also be comfortable with traits at the level of "a type can implement a trait". Everything here builds on the input functions from the earlier chapters.
The problem: two kinds of failure in one function
Reading numbers from input can fail in two unrelated ways.
- Reading can fail.
lines()yieldsio::Result<String>, so the error type isstd::io::Error. - Parsing can fail.
str::parse::<i32>()returnsResult<i32, ParseIntError>, so the error type isstd::num::ParseIntError.
A function has one return type. If it is declared as io::Result<Vec<i32>>, a ? applied to a parse result does not compile, because ParseIntError cannot become an io::Error. If it is declared with ParseIntError, the ? on the line read fails the same way.
You need one error type that can hold either failure. Box<dyn Error> is the shortest way to get one.
What Box<dyn Error> is
The pieces are as follows.
std::error::Erroris a trait. Bothio::ErrorandParseIntErrorimplement it.dyn Erroris a trait object. It stands for "some value of unknown concrete type that implementsError".Box<...>puts that value on the heap. A trait object has no size known at compile time, so it must sit behind a pointer.
So Box<dyn Error> is an owned pointer to any error value. Every error type has the same box type, which lets one function return different errors.
The standard library supplies the conversion. It contains an implementation equivalent to impl<E: Error> From<E> for Box<dyn Error>. When ? meets an Err(e), it calls From::from(e) to convert the error into the function's declared error type. With Box<dyn Error> as that type, any error implementing Error is boxed automatically.
A worked example
This is the function from the plan. It accepts any BufRead, skips blank lines, and returns either the numbers or the first error.
use std::error::Error;
use std::io::{self, BufRead};
fn read_numbers<R: BufRead>(reader: R) -> Result<Vec<i32>, Box<dyn Error>> {
let mut numbers = Vec::new();
for line in reader.lines() {
let line = line?;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
numbers.push(trimmed.parse::<i32>()?);
}
Ok(numbers)
}
fn main() -> Result<(), Box<dyn Error>> {
let numbers = read_numbers(io::stdin().lock())?;
println!("{numbers:?}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn skips_blank_lines() {
let data = "1\n2\n\n3\n";
assert_eq!(read_numbers(data.as_bytes()).unwrap(), vec![1, 2, 3]);
}
}There are two ? operators in the loop, and they apply to different error types:
line?has typeResult<String, io::Error>. On failure it boxes theio::Error.trimmed.parse::<i32>()?has typeResult<i32, ParseIntError>. On failure it boxes theParseIntError.
Neither needs a map_err call or a hand-written conversion. Both functions return early with an Err(Box<dyn Error>).
main can return the same type
main is allowed to return Result<(), E> when E implements Debug. Box<dyn Error> qualifies. If main returns Err, the runtime prints Error: followed by the Debug form of the error to stderr and exits with a non-zero status.
For the input 12 then abc, the output is:
Error: ParseIntError { kind: InvalidDigit }That message is accurate but unhelpful. It does not say which line failed or what the bad text was. The next section fixes that.
Adding context with string errors
The standard library also implements From<&str> and From<String> for Box<dyn Error>. This means you can turn a message into an error with .into(), or let ? convert a String error.
map_err rewrites the parse error into a message that names the line and the bad text:
use std::error::Error;
use std::io::{self, BufRead};
fn read_numbers<R: BufRead>(reader: R) -> Result<Vec<i32>, Box<dyn Error>> {
let mut numbers = Vec::new();
for (index, line) in reader.lines().enumerate() {
let line = line?;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let n = trimmed
.parse::<i32>()
.map_err(|e| format!("line {}: {trimmed:?}: {e}", index + 1))?;
numbers.push(n);
}
Ok(numbers)
}
fn run() -> Result<(), Box<dyn Error>> {
let numbers = read_numbers(io::stdin().lock())?;
println!("sum = {}", numbers.iter().sum::<i32>());
Ok(())
}
fn main() {
if let Err(e) = run() {
eprintln!("error: {e}");
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reports_line_number() {
let err = read_numbers("1\nabc\n".as_bytes()).unwrap_err();
assert_eq!(
err.to_string(),
"line 2: \"abc\": invalid digit found in string"
);
}
}Three changes are worth noting.
enumerate()supplies a zero-based index, so the message usesindex + 1.map_errproduces aString. The?then converts thatStringintoBox<dyn Error>throughFrom<String>.mainno longer returns the error. It callsrun, prints the error withDisplay({e}), and exits with status 1. For a command-line tool this gives cleaner output than theDebugform.
With the bad input above, the program prints:
error: line 2: "abc": invalid digit found in stringRecovering the original type
Boxing erases the concrete type, but it does not destroy it. dyn Error supports downcast_ref, which returns Some(&T) if the boxed value really is a T.
use std::error::Error;
use std::num::ParseIntError;
fn parse_all(text: &str) -> Result<Vec<i32>, Box<dyn Error>> {
let mut out = Vec::new();
for token in text.split_whitespace() {
out.push(token.parse::<i32>()?);
}
Ok(out)
}
fn main() {
match parse_all("4 5 x") {
Ok(v) => println!("{v:?}"),
Err(e) => {
if let Some(parse_err) = e.downcast_ref::<ParseIntError>() {
println!("bad number: {parse_err}");
} else {
println!("other error: {e}");
}
}
}
}This prints bad number: invalid digit found in string.
Downcasting is a fallback, not a design to build on. It is a runtime check, so the compiler cannot tell you when you forget a case. If callers need to branch on error kinds often, use a custom enum instead (see the table below).
Gotchas and limits
- Context is lost unless you add it. The boxed
ParseIntErrordoes not remember the line number or the text. Add context withmap_err, as above, before the error is boxed. Box<dyn Error>does not implementErroritself. You can print it and downcast it. You cannot pass it to a generic function that requiresE: Error. Code that must do so needsanyhowor a custom type.- It is not
SendorSyncby default. If the error must cross a thread boundary, writeBox<dyn Error + Send + Sync>. The?conversion still works for any error type that is alsoSend + Sync. This includesio::ErrorandParseIntError. Boxed&strandStringmessages work too. ?cannot convert intoOption. A function that returnsOptioncannot use?on aResult. Convert first with.ok()or.ok_or(...).- The cost is an allocation on the error path only. The success path allocates nothing extra. Compared with the I/O it sits beside, the cost is negligible.
Ok(0)is not an error. End of input fromread_lineis a successful read of zero bytes. If your function should treat it as a failure, build that error yourself, for examplereturn Err("unexpected end of input".into());.
Choosing an error type
| Approach | Good for | Drawback |
|---|---|---|
| `io::Result<T>` | Functions that only do I/O | Cannot carry parse errors |
| `Box<dyn Error>` | Small programs, scripts, tutorials, binaries that print and exit | Callers cannot `match` on error kinds without downcasting |
| Custom `enum` with `From` impls | Libraries and code where callers react to specific failures | More code to write |
| `anyhow::Error` (external crate) | Applications that want context chaining and backtraces | Adds a dependency |
For the input-reading programs in this tutorial, Box<dyn Error> is the right level of effort. If a function becomes part of a library that others call, move to a custom enum.
Putting it together
The read_numbers function now has these properties:
- It is generic over
BufRead, so tests feed it&[u8]andmainfeeds it a lockedstdin. - It returns
Box<dyn Error>, so I/O failures and parse failures use the same?syntax. - It can attach context to errors before they are boxed.
The next chapter uses this combination to write tests for input code that never touch a terminal.
Exercise
A function is declared as fn first_number(r: impl BufRead) -> Result<i32, ParseIntError>. Its body calls r.lines().next().unwrap()? on a BufRead. Why does this fail to compile, and what is the smallest change to the signature that fixes it?
Show answer
The ? on io::Result<String> needs to convert io::Error into ParseIntError, and no From<io::Error> implementation for ParseIntError exists. Changing the return type to Result<i32, Box<dyn Error>> fixes it, because both error types convert into the box.
Exercise
Change read_numbers so that a line containing a negative number produces the error line N: negative numbers are not allowed, where N is the one-based line number. Which two conversions let you write the error without defining a new error type?
Show answer
After parsing, add if n < 0 { return Err(format!("line {}: negative numbers are not allowed", index + 1).into()); }. The .into() call uses From<String> for Box<dyn Error>. (A &str literal would use From<&str>, but here the message is built with format!, so it is a String.) The parse failure still uses From<ParseIntError> through ?.
Exercise
A caller of read_numbers receives an Err(e) and wants to print "I/O problem" only when the cause was an io::Error. Write the check.
Show answer
if e.downcast_ref::<std::io::Error>().is_some() { println!("I/O problem"); }. The downcast_ref method returns Some only when the boxed value is an io::Error.