Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ PACKAGES, FILES & TOOLS
BUILD NOTE 34 / 53

Let the caller decide what failure means.

Combine structured domain errors with Display and Error.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

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.

lessons/custom-errors/src/main.rs
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());
}
↳ EXPECTED OUTPUT
limit is zero
  1. 1

    Variants remain available for structured matching.

  2. 2

    Display defines a human-readable message.

  3. 3

    Error connects this type to standard error interfaces.

From the extracted rust-workbench folder
cargo run -p lesson_custom_errors

03 Mind the boundary

04 Your next build

A SMALL MISSION

Match a structured error variant in a test instead of comparing a message string.

Reveal one possible solution +
solutions/custom-errors/src/main.rs
#[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

QUICK SIGNAL CHECK

What is a benefit of a domain error enum?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.