Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 09 / 21 · ABSTRACTION

Errors as part of the type.

Use Result, propagation, and custom errors to expose failure honestly.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

Rust separates recoverable failure from an unrecoverable panic. A Result<T,E> contains either an Ok value or an Err value. A caller must decide whether to handle, transform, or propagate that error before it can treat the operation as successful. This makes failure visible in signatures and prevents a missing file or invalid parse from being mistaken for a valid result.

The ? operator is concise propagation. On Ok it extracts the value; on Err it returns early from the enclosing compatible function. It does not hide the error or retry the operation. A function returning a custom error type can attach context and preserve distinctions between input, I/O, and validation failures, giving a caller enough information to make a useful decision.

02 / THE RULES

What Rust is checking.

A panic is for a broken invariant or a situation the program cannot sensibly recover from in its current context. It unwinds or aborts according to configuration and is not a replacement for ordinary input validation. unwrap and expect can be appropriate where an invariant has already been established, but they make the crash path explicit and should be chosen knowingly.

Error types are part of an API's design. Too little detail makes a failure impossible to diagnose; too much implementation detail couples callers to internals. The examples show how Result carries a successful value and how a meaningful error can travel to the layer that has the information needed to report or recover from it. The compiler checks the shape of the path, while your design decides the message and policy.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Result & recoverable errors

Result<T, E> separates successful values from recoverable failures. Parsing input can fail without being a programmer bug, so return an error instead of crashing. The ? operator returns early with an error and unwraps only the success path; the surrounding function must have a compatible return type. Error messages should preserve enough context for the caller to act. Use a domain error enum when callers need structured decisions, and reserve panic for violated invariants or unrecoverable conditions.

result.rs
fn quantity(text: &str) -> Result<u32, String> {
    let n = text
        .parse::<u32>()
        .map_err(|_| "not a whole number".to_owned())?;
    if n == 0 {
        return Err("quantity must be positive".into());
    }
    Ok(n)
}
fn main() {
    println!("{:?}", quantity("3"));
    println!("{:?}", quantity("0"));
}
OUTPUT
Ok(3)
Err("quantity must be positive")
  1. map_err turns a parse error into a domain message.
  2. ? propagates the error without nesting another match.
  3. A parsed zero is still rejected by the business rule.

The boundary: Do not silently use unwrap_or(0) if zero would disguise malformed user input.

EXAMPLE 02

Custom error types

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.

custom-errors.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());
}
OUTPUT
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.

The boundary: Do not expose database URLs, credentials, or internal stack details as a public error response. Translate errors at the boundary.

04 / THE CONNECTION

Keep this model.

Result names the possibility of failure in the type. Propagation moves the decision to a caller; it does not make the failure disappear.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.