Sub topic 11
Converting errors automatically with From
This chapter assumes you know Result, the ? operator, enums, and traits at a basic level. It also assumes you have seen a custom error enum that implements Display and Error.
The problem: mixed error types
A function returns one error type. Real code often calls functions that fail in different ways. Parsing a number fails with ParseIntError. A missing key is something you define yourself. If both can happen in one function, you need a way to turn each into a single error type.
You could write .map_err(ConfigError::BadNumber)? at every call. That works, but it is noisy. The From trait removes that noise.
How ? uses From
When ? finds an Err(e), it does not return e as is. It returns From::from(e), converting e into the error type in the function's signature. If the two types are the same, the conversion changes nothing. If they differ, the compiler looks for an impl From<SourceError> for TargetError.
Writing the From implementation
Here is a complete example. ConfigError has two variants. One wraps a ParseIntError, and From connects it to ?.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
BadNumber(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "missing key: {key}"),
ConfigError::BadNumber(e) => write!(f, "bad number: {e}"),
}
}
}
impl std::error::Error for ConfigError {}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or(ConfigError::Missing("port"))?;
let port = text.parse::<u16>()?;
Ok(port)
}
fn main() -> Result<(), ConfigError> {
println!("{}", read_port(Some("8080"))?);
println!("{}", read_port(None)?);
Ok(())
}Two lines use ? and they behave differently:
ok_or(ConfigError::Missing("port"))?already holds aConfigError, so no conversion happens.text.parse::<u16>()?holds aParseIntError. The compiler findsFrom<ParseIntError> for ConfigErrorand wraps the error inBadNumber.
The program prints 8080, then returns the Missing error from main. Rust prints that error in Debug form: Error: Missing("port").
Several sources, one target
You can add one From implementation per source type. Each source type may map to only one variant, because the compiler must pick a single conversion from the type alone. If two sources of the same type need different variants, such as two different ParseIntError situations, use map_err at those call sites.
Common errors
- Missing implementation. The compiler reports that
?cannot convert the error type, with a note thatFrom<X>is not implemented for your error. Add theimpl. - Wrong direction. You write
impl From<ConfigError> for ParseIntError. The impl belongs on the type you are converting to, which is the one in the function signature. - Lost context. A blanket
Fromwraps the error but cannot say which input failed. If you need that, store extra fields in the variant and build it withmap_err.
Exercise
A function returns Result<u16, ConfigError>. Inside it, you call "x".parse::<u16>()? and no From<ParseIntError> for ConfigError exists. What happens, and how do you fix it?
Show answer
The code fails to compile, because ? cannot convert ParseIntError into ConfigError. Fix it by adding impl From<ParseIntError> for ConfigError, which wraps the error in a variant such as BadNumber. Alternatively, use .map_err(ConfigError::BadNumber)? at the call site.