Sub topic 13
Custom error enums and From conversions
This chapter assumes you know how Result<T, E> and the ? operator work, and that you can write a match over enum variants. Here you will build your own error type so a function can report several kinds of failure through one Result.
Why a custom error enum
A function often fails for different reasons. Reading a setting might fail because the value is absent, or because it is present but not a number. A String error hides which case happened. An enum gives each failure its own variant, and the caller can match on it. The compiler then checks that every failure is handled.
use std::num::ParseIntError;
enum ConfigError {
Missing(String),
Invalid(ParseIntError),
}Missing carries the name of the absent setting. Invalid carries the original ParseIntError, so no detail is lost.
Converting errors with From
The ? operator does more than return early. When the error type of the expression differs from the function's error type, ? calls From::from to convert it. You enable this by implementing From for your enum.
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::Invalid(e)
}
}With this in place, a ParseIntError produced inside a function that returns Result<_, ConfigError> becomes ConfigError::Invalid automatically.
A complete example
use std::num::ParseIntError;
enum ConfigError {
Missing(String),
Invalid(ParseIntError),
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::Invalid(e)
}
}
fn parse_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or_else(|| ConfigError::Missing("port".to_string()))?;
Ok(text.parse::<u16>()?)
}
fn main() {
for input in [Some("8080"), Some("abc"), None] {
match parse_port(input) {
Ok(port) => println!("port {port}"),
Err(ConfigError::Missing(name)) => println!("missing {name}"),
Err(ConfigError::Invalid(e)) => println!("invalid: {e}"),
}
}
}The program prints:
port 8080
invalid: invalid digit found in string
missing portTwo ? operators appear in parse_port, and they work differently:
ok_or_elseturns theOptioninto aResultwhose error is already aConfigError. No conversion is needed.text.parse::<u16>()?yields aParseIntError. The?converts it through yourFromimplementation.
The match in main lists both error variants. If you add a third variant later, the compiler flags every match that does not handle it.
Common errors
- Missing
Fromimplementation. Without it,?fails to compile with an error thatConfigError: From<ParseIntError>is not satisfied. Add theimpl. - One
Fromper source type. Two variants cannot both wrapParseIntErrorand both be reached through?. The conversion is chosen by type, so it must be unambiguous. - Printing the error.
println!("{}", err)needsDisplay, and{:?}needsDebug. The example avoids this by matching and printing the innerParseIntError. To print aConfigErroritself, implementDisplayor add#[derive(Debug)].
Exercise
Add a variant OutOfRange(u16) to ConfigError, and make parse_port return it when the parsed port is below 1024. What must you also change in main?
Show answer
Add if port < 1024 { return Err(ConfigError::OutOfRange(port)); } after parsing, then Ok(port). In main, add an arm Err(ConfigError::OutOfRange(p)) => println!("port {p} is reserved"). Without that arm the match is not exhaustive and the program does not compile.