Sub topic 11
Converting errors automatically with From
This chapter explains how the ? operator converts one error type into another, and how to set that up with the From trait. It assumes you know how ? propagates errors, how to write an enum with Display and Error impls, and what a trait impl is. The rest is built from those pieces.
The problem: functions that fail in different ways
A real function often calls several fallible operations, and each returns a different error type. Reading a file gives io::Error. Parsing text gives ParseIntError. A function returns one Result<T, E>, so it has one E. You need a way to fit several error types into one.
The usual answer is your own error enum with one variant per source of failure. From is the tool that lets ? wrap each source error into the right variant for you.
What ? really does with the error
When ? sees an Err(e), it returns early from the function. Before returning, it passes e through From::from. These two blocks behave the same:
use std::num::ParseIntError;
#[derive(Debug)]
struct AppError(ParseIntError);
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self {
AppError(e)
}
}
fn with_question_mark(s: &str) -> Result<u16, AppError> {
let n = s.parse::<u16>()?;
Ok(n)
}
fn written_out(s: &str) -> Result<u16, AppError> {
let n = match s.parse::<u16>() {
Ok(v) => v,
Err(e) => return Err(AppError::from(e)),
};
Ok(n)
}
fn main() {
println!("{:?}", with_question_mark("42"));
println!("{:?}", written_out("nope"));
}The target type comes from the function's return type, Result<u16, AppError>. The compiler looks for impl From<ParseIntError> for AppError. If it finds one, the conversion is inserted. If not, you get an error like `the trait From<ParseIntError> is not implemented for AppError `.
One enum, several From impls
You can write one From impl per source error type. Each maps to its own variant, so a single function can use ? on many different results.
use std::error::Error;
use std::fmt;
use std::fs;
use std::io;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Io(io::Error),
BadNumber(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Io(e) => write!(f, "could not read file: {e}"),
ConfigError::BadNumber(e) => write!(f, "bad number: {e}"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::Io(e) => Some(e),
ConfigError::BadNumber(e) => Some(e),
}
}
}
impl From<io::Error> for ConfigError {
fn from(e: io::Error) -> Self {
ConfigError::Io(e)
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
fn read_port(path: &str) -> Result<u16, ConfigError> {
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}"),
}
}Both ? lines use the same syntax. The first converts io::Error. The second converts ParseIntError. If port.txt does not exist, the program prints a "could not read file" message. If the file holds abc, it prints a "bad number" message.
The source method is optional, but it is worth writing. It lets error reporters walk from your error down to the original cause.
Rules and limits of From
- One impl per source type.
ConfigErrorcan haveFrom<io::Error>andFrom<ParseIntError>. It cannot have twoFrom<ParseIntError>impls, because the compiler could not pick between them. - The orphan rule applies. You can write
impl From<X> for MyErrorbecauseMyErroris your type. You cannot writeimpl From<ParseIntError> for io::Error, because you own neither type. Fromis reflexive. The standard library providesimpl<T> From<T> for T. So?works when the error type already matches, with no extra code.- Converting is not free.
From::fromruns code on the error path only. On the success path,?adds no conversion. ?on anOptionin aResultfunction fails to compile. The two types are not converted byFrom. Useok_ororok_or_elsefirst, as covered in the chapter on moving between Option and Result.
When From is the wrong tool: map_err
From ties a source type to exactly one variant. Sometimes two different failures have the same source type, and you want to tell them apart. Parsing two numbers is an example. Both fail with ParseIntError, but you want to know which one failed. Here From cannot help, so use map_err with the variant as a function.
use std::num::ParseIntError;
#[derive(Debug)]
enum PairError {
First(ParseIntError),
Second(ParseIntError),
}
fn parse_pair(a: &str, b: &str) -> Result<(u16, u16), PairError> {
let x = a.parse::<u16>().map_err(PairError::First)?;
let y = b.parse::<u16>().map_err(PairError::Second)?;
Ok((x, y))
}
fn main() {
println!("{:?}", parse_pair("1", "2"));
println!("{:?}", parse_pair("1", "two"));
}PairError::First is a tuple variant, and a tuple variant works as a function from ParseIntError to PairError. Here ? still calls From::from, but it uses the reflexive impl because the types already match.
| Situation | Use | Column | Column |
|---|---|---|---|
| Each source type maps to one variant | `impl From<Source> for MyError`, then `?` | ||
| The same source type needs different variants | `map_err(MyError::Variant)?` | ||
| You want to add context such as a file name | `map_err(\ | e\ | MyError::Io { path, source: e })?` |
| You do not need to match on error variants | `Box<dyn Error>`, which has its own `From` impls |
Boxed errors use the same mechanism
The standard library implements From<E> for Box<dyn Error> for any E that implements Error. That is why ? works in a function returning Result<T, Box<dyn Error>> with no impls from you. It is the same From call, only with a catch-all target type.
use std::error::Error;
fn double(s: &str) -> Result<i32, Box<dyn Error>> {
let n = s.parse::<i32>()?;
Ok(n * 2)
}
fn main() {
println!("{:?}", double("21").ok());
match double("x") {
Ok(v) => println!("{v}"),
Err(e) => println!("failed: {e}"),
}
}The trade-off is that callers lose the ability to match on specific variants. They can still try downcast_ref, but that is clumsy compared with an enum.
Common mistakes
- Forgetting the impl. The compiler error mentions
From<...>not being implemented. Add the impl or usemap_err. - Wrapping and losing the message. If
Displayfor your enum ignores the inner error, users see "bad number" and nothing else. Include the inner error in the output, or expose it throughsource. - Writing a lossy From. An impl like
From<io::Error> for ConfigErrorthat discards theio::Errorand returnsConfigError::Failedthrows away the cause. Keep the original error in the variant. - Letting inference decide the target. In a closure or a
letwith no type,?may report that the error type cannot be inferred. Annotate the closure's return type, or put the code in a named function. - Too many broad From impls. If you add
From<io::Error>and use it for both reading config and writing logs, the variant cannot say which one failed. Usemap_errwith a more specific variant for those cases.
Exercise
Exercise
A function returns Result<(), AppError>. It calls fs::readtostring(path)? and then text.trim().parse::<u32>()?. AppError currently has only impl From<std::io::Error> for AppError. What happens when you compile, and how do you fix it?
Show answer
The compiler rejects the second ?, saying that From<ParseIntError> is not implemented for AppError. The first ? works because the io::Error impl exists. To fix it, add a variant such as AppError::BadNumber(ParseIntError) and write impl From<ParseIntError> for AppError that returns AppError::BadNumber(e). If the function also needs to tell two different parse failures apart, skip that impl for them and use map_err with a specific variant instead.