Let the caller decide what failure means.
Combine structured domain errors with Display and Error.
01 Understand the contract
A custom enum can distinguish error categories without asking callers to parse strings. Implement Display for readable messages and std::error::Error for interoperability with error-handling APIs. Preserve underlying errors with source when useful, and use From implementations for deliberate conversions. A library often exposes a specific error type, while an application entry point may use Box<dyn Error> to aggregate failures. Separate internal detail from the public message at an HTTP or desktop boundary.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::{error::Error, fmt};
#[derive(Debug, PartialEq)]
enum LimitError {
Zero,
TooLarge,
}
impl fmt::Display for LimitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Zero => "limit is zero",
Self::TooLarge => "limit exceeds 100",
}
)
}
}
impl Error for LimitError {}
fn validate(n: u32) -> Result<u32, LimitError> {
match n {
0 => Err(LimitError::Zero),
1..=100 => Ok(n),
_ => Err(LimitError::TooLarge),
}
}
fn main() {
println!("{}", validate(0).unwrap_err());
}limit is zero
- 1
Variants remain available for structured matching.
- 2
Display defines a human-readable message.
- 3
Error connects this type to standard error interfaces.
cargo run -p lesson_custom_errors03 Mind the boundary
04 Your next build
Match a structured error variant in a test instead of comparing a message string.
Reveal one possible solution +
#[derive(Debug, PartialEq)]
enum Error {
Empty,
TooLong,
}
fn check(s: &str) -> Result<(), Error> {
if s.is_empty() {
Err(Error::Empty)
} else if s.len() > 5 {
Err(Error::TooLong)
} else {
Ok(())
}
}
fn main() {
assert_eq!(check(""), Err(Error::Empty));
assert_eq!(check("123456"), Err(Error::TooLong));
assert_eq!(check("rust"), Ok(()));
}05 Check your reasoning
What is a benefit of a domain error enum?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.