Sub topic 13
Custom error enums and From conversions
This chapter assumes you know Result<T, E>, the ? operator on simple cases, match on enums, and how to write impl blocks and implement a trait. It shows how to define one error enum for a whole function or module, and how From lets ? convert errors for you.
Why a custom error enum
A function that can fail in several ways needs one error type that covers all of them. Result<T, E> has a single E. If you parse an integer and also validate a range, the two failures have different types: ParseIntError from the standard library and whatever you define for the range check.
An enum solves this. Each variant is one kind of failure and can carry the data that describes it. The caller then uses match to handle each kind differently, and the compiler's exhaustiveness check flags every match that misses one.
A first error type
Here is the smallest useful version. Missing holds the name of a setting. Invalid wraps the original ParseIntError.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(String),
Invalid(ParseIntError),
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::Invalid(e)
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Missing(name) => write!(f, "missing setting: {name}"),
ConfigError::Invalid(e) => write!(f, "invalid number: {e}"),
}
}
}
impl std::error::Error for ConfigError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ConfigError::Missing(_) => None,
ConfigError::Invalid(e) => Some(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(e) => println!("error: {e}"),
}
}
}The program prints port 8080, then error: invalid number: invalid digit found in string, then error: missing setting: port.
Four pieces make up a complete error type:
- The enum itself. One variant per failure, with the data a caller needs.
Debug. Usually derived.mainreturning aResultandunwrapboth need it.Display. The human-readable message, written as amatchover the variants.std::error::Error. Marks the type as an error. The optionalsourcemethod exposes the wrapped error, so tools that walk an error chain can find the root cause.
How `?` uses `From`
The ? operator does two things on an Err. It converts the error with From::from, then returns early. On Ok it unwraps the value. Roughly, expr? behaves like this:
let value = match expr {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
};That conversion is why text.parse::<u16>()? compiles inside a function that returns Result<u16, ConfigError>. The parse produces a ParseIntError, and the compiler finds impl From<ParseIntError> for ConfigError to turn it into ConfigError::Invalid.
The same rule applies when the error types are identical. The standard library provides impl<T> From<T> for T, so ? works with no conversion needed in that case.
? also works on Option inside a function that returns Option. It does not convert an Option into a Result. That is why the example calls ok_or_else first: it turns None into Err(ConfigError::Missing(...)), and the closure builds the error only when needed.
Several sources, one enum
Add one From impl for each source error type and ? handles all of them. This example mixes two parse errors and a check of its own.
use std::num::{ParseFloatError, ParseIntError};
#[derive(Debug)]
enum SettingError {
BadInt(ParseIntError),
BadFloat(ParseFloatError),
OutOfRange { name: &'static str, value: f64 },
}
impl From<ParseIntError> for SettingError {
fn from(e: ParseIntError) -> Self {
SettingError::BadInt(e)
}
}
impl From<ParseFloatError> for SettingError {
fn from(e: ParseFloatError) -> Self {
SettingError::BadFloat(e)
}
}
fn parse_settings(port: &str, ratio: &str) -> Result<(u16, f64), SettingError> {
let port: u16 = port.parse()?;
let ratio: f64 = ratio.parse()?;
if !(0.0..=1.0).contains(&ratio) {
return Err(SettingError::OutOfRange { name: "ratio", value: ratio });
}
Ok((port, ratio))
}
fn main() {
let cases = [("8080", "0.5"), ("80x", "0.5"), ("8080", "half"), ("8080", "1.5")];
for (port, ratio) in cases {
match parse_settings(port, ratio) {
Ok((p, r)) => println!("ok: {p} {r}"),
Err(SettingError::BadInt(e)) => println!("bad integer: {e}"),
Err(SettingError::BadFloat(e)) => println!("bad float: {e}"),
Err(SettingError::OutOfRange { name, value }) => {
println!("{name} out of range: {value}")
}
}
}
}Each ? picks its From impl from the error type it sees. The OutOfRange error needs no From impl because the function creates it directly with return Err(...). The final match has no wildcard arm, so adding a fourth variant later makes this match fail to compile until you handle it.
When From is not enough
From converts by type alone, so it cannot record where the error happened. Suppose two settings are both parsed as integers:
#[derive(Debug)]
enum LimitError {
BadPort(std::num::ParseIntError),
BadWorkers(std::num::ParseIntError),
}
fn parse_limits(port: &str, workers: &str) -> Result<(u16, u8), LimitError> {
let port = port.parse::<u16>().map_err(LimitError::BadPort)?;
let workers = workers.parse::<u8>().map_err(LimitError::BadWorkers)?;
Ok((port, workers))
}
fn main() {
println!("{:?}", parse_limits("80", "4"));
println!("{:?}", parse_limits("80", "many"));
}A variant name like LimitError::BadPort is a function from the wrapped value to the enum, so it can be passed directly to map_err. Here you use map_err instead of From, and each call site chooses its own variant.
Edge cases and decisions
?needs a conversion path. If the function's error type has noFromimpl for the error you propagate, the compiler reports that?couldn't convert the error. The fix is aFromimpl or amap_errcall.maincan return aResult. Withfn main() -> Result<(), ConfigError>, anErrends the program with a nonzero exit code and prints theDebugform of the error. That is whyDebugmust be derived.- Keep
Fromfor lossless wrapping. An impl that discards information, such as turning any error into a unit variant, hides the cause. Wrap the original error sosourcecan return it. - Library or application? A library should expose an enum so callers can
matchon it. An application that only reports errors can useBox<dyn std::error::Error>, which accepts any error type through?but gives up the ability to match on variants. - Variant data is part of your API. Public error enums that gain variants break callers' exhaustive matches. Libraries often mark such enums
#[non_exhaustive]to reserve the right to add variants.
Exercise
A function parses a "min" and a "max" value, both with str::parse::<u32>(), and returns Result<(u32, u32), RangeError>. You want RangeError::BadMin and RangeError::BadMax to wrap the ParseIntError and tell the caller which field failed. Can you do this with two From<ParseIntError> impls? If not, what do you write instead?
Show answer
No. Only one impl From<ParseIntError> for RangeError can exist, so two would conflict, and a single one cannot know which field failed. Define both variants as tuple variants holding a ParseIntError and convert at each call site: min.parse::<u32>().map_err(RangeError::BadMin)? and max.parse::<u32>().map_err(RangeError::BadMax)?.
Exercise
In the first example, parse_port calls value.ok_or_else(|| ConfigError::Missing("port".to_string()))?. Why is ok_or_else needed before the ?, and why use a closure rather than ok_or(ConfigError::Missing(...))?
Show answer
value is an Option<&str>, and ? on an Option inside a function that returns Result does not compile. ok_or_else turns None into Err(ConfigError::Missing(...)) first. The closure delays building the error, including the String allocation, until the value is actually None. ok_or builds it every time, even on Some.