Sub topic 9
Designing a custom error type
This chapter assumes you know Rust enums and match, can implement a trait for a type, and have used ? on Result values. It also assumes you know that ? converts errors through the From trait, which the previous chapter covered.
Why build your own error type
A function often fails in more than one way. A config reader can hit a missing key or a malformed number. If the return type is Result<u16, ParseIntError>, the "missing key" case has nowhere to go.
A custom error type is usually an enum with one variant per kind of failure. Callers can match on it and decide what to do for each case.
The four pieces
To work well with ?, an error enum needs four things:
- A
#[derive(Debug)]so it can be printed for debugging. - An
impl fmt::Displaythat gives a human-readable message. - An
impl Error, the standard trait for error types. It requiresDebugandDisplay. Its optionalsourcemethod exposes the underlying cause. - One
impl From<SomeError>for each error type you want?to convert automatically.
A worked example
This enum covers two failures when reading a port number from a config value.
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(String),
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, "invalid number: {e}"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::BadNumber(e) => Some(e),
ConfigError::Missing(_) => None,
}
}
}
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_else(|| ConfigError::Missing("port".to_string()))?;
let port = text.parse::<u16>()?;
Ok(port)
}
fn main() {
println!("{:?}", read_port(Some("8080")));
println!("{:?}", read_port(None));
match read_port(Some("abc")) {
Ok(p) => println!("port {p}"),
Err(e) => println!("error: {e}"),
}
}Two different conversions happen in read_port:
ok_or_elseturns theOptioninto aResult. If the value isNone, it buildsConfigError::Missing. The closure runs only on the error path, so theStringis not allocated on success. The following?then returns that error as is.text.parse::<u16>()?produces aParseIntErroron failure.?callsFrom::from, which finds ourFrom<ParseIntError>impl and wraps the error inConfigError::BadNumber.
What source is for
source lets error-reporting code walk a chain of causes. BadNumber returns the inner ParseIntError, so a caller can print "invalid number" and then the underlying reason. Missing has no inner error, so it returns None.
Design guidance
- Add one
Fromimpl per source error. Two variants that wrap the same type needmap_errinstead, because?can pick only oneFromimpl for a given source type. - Keep variants meaningful to the caller.
Missing(String)carries the key name, which helps in a message. - Use
map_errwhen you want a specific variant without aFromimpl:text.parse::<u16>().map_err(ConfigError::BadNumber)?.
Exercise
Add a third variant, OutOfRange(u16), to ConfigError. Change read_port so ports below 1024 return it. Which pieces of the enum's implementation must you update?
Show answer
Add the variant, then add a Display arm for it, for example ConfigError::OutOfRange(p) => write!(f, "port {p} is reserved"). Add a source arm only if you rely on exhaustive matching: OutOfRange(_) => None (or a _ => None catch-all). No From impl is needed because the check is your own code, so build the error directly with return Err(ConfigError::OutOfRange(port)); after parsing.