Create useful error types
Quick answer
An error enum can distinguish failure categories so callers can respond appropriately. For reusable libraries, implement meaningful Display and Error rather than forcing callers to inspect strings.
Structured errors and messages
Use one variant per meaningful failure; attach contextual fields when needed. Debug supports developer diagnostics, Display produces a readable message, and std::error::Error integrates with standard error tooling. Trait syntax appears here as a preview and is explained in the following chapter.
#[derive(Debug)]enum LimitError { Empty, TooLarge }fn check(n: u32) -> Result<u32, LimitError> { match n { 0 => Err(LimitError::Empty), 1..=5 => Ok(n), _ => Err(LimitError::TooLarge) }}fn main() { println!("{:?}", check(9)); }Expected stdout (not executed):
Err(TooLarge)The caller can match TooLarge directly.
use std::fmt;#[derive(Debug)]struct MissingName;impl fmt::Display for MissingName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "name required") }}impl std::error::Error for MissingName {}fn main() { println!("{}", MissingName); }Expected stdout (not executed):
name requiredDisplay is separate from the debug representation.
Common mistake
Avoid making program decisions by comparing human-readable error messages; match structured variants instead.
Try it yourself
Define an error enum for a missing ID and a duplicate ID and match each one.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Create useful error types — practice quiz
Choose one answer per question, then review the explanation.
An error enum has Missing and OutOfRange variants. Why prefer matching these over parsing display text?
Which trait supplies ordinary `{}` formatting for a custom error?
What can `OutOfRange(u32)` communicate beyond an error name?