error-concept

Typed domain errors

Use an enum to represent distinguishable failure cases. Library callers can match variants and choose recovery without parsing messages. This example keeps the error type small and explicit. Expected stdout (not executed): choose a positive quantity Common mistake: Making callers compare text to identify a failure category.

Formal Syntax & Structure

rust syntaxrust
enum DomainError { ... }

Working Example

Example Snippetrust
#[derive(Debug)]enum ReserveError { InvalidQuantity }fn reserve(n: u32) -> Result<u32, ReserveError> {    if n == 0 { Err(ReserveError::InvalidQuantity) } else { Ok(n) }}fn main() {    let result = reserve(0);    match result { Ok(n) => println!("{n}"), Err(ReserveError::InvalidQuantity) => println!("choose a positive quantity") }}
Rust Reference