Skip to content

Give Callers an Error They Can Match

The Course
•
26 min study

On Day 4 the rows were hard-coded, so every ID was valid by construction. From today the reading queue reads commands typed by a person, and people type seven, 0 and -1. Each of those is a different mistake, and the program should say which one happened. If a parser returned a String message, the caller could only print it or try to read the words back out, which breaks the day someone rewords the message. A dedicated error enum says why the operation failed as a value the caller can match on, and the compiler checks every case.

Two tools connect the standard library's errors to your own. map_err transforms the error side of a Result and leaves a success untouched. The ? operator unwraps a success, or returns the error from the enclosing function immediately. Together they let a parser say "if the number does not parse, that is an InvalidNumber" in one line, then carry on with the next rule.

Predict and run

parse_id accepts positive u32 values. Which input reaches the zero check? Which input returns early through the question mark?

Predict, then run Rust
#[derive(Debug, PartialEq, Eq)]
enum IdError {
    InvalidNumber,
    Zero,
}

fn parse_id(text: &str) -> Result<u32, IdError> {
    let id = text.parse::<u32>().map_err(|_| IdError::InvalidNumber)?;
    if id == 0 {
        return Err(IdError::Zero);
    }
    Ok(id)
}

fn main() {
    for input in ["7", "0", "later"] {
        println!("{input}: {:?}", parse_id(input));
    }
}
Check your prediction
Text
7: Ok(7)
0: Err(Zero)
later: Err(InvalidNumber)

later fails inside parse, so map_err replaces the standard error with InvalidNumber and ? returns it; the zero check never runs. 0 parses fine, which is exactly why it needs its own rule. Add "4294967296", one above u32::MAX, and " 7" with a leading space to the list. Predict which variant each produces. Both are InvalidNumber: parse rejects values that do not fit, and it does not trim whitespace for you.

Let the caller decide what to say

The error enum carries the reason; the text a person sees is chosen where the error is displayed. The queue does this with a message method, and the input loop prints it next to a line number. Because match must cover every variant, you cannot forget to word one.

Turn reasons into messages at the edge Rust
#[derive(Debug, PartialEq, Eq)]
enum IdError {
    InvalidNumber,
    Zero,
}

impl IdError {
    fn message(&self) -> &'static str {
        match self {
            Self::InvalidNumber => "use a whole-number ID",
            Self::Zero => "ID must be positive",
        }
    }
}

fn parse_id(text: &str) -> Result<u32, IdError> {
    let id = text.parse::<u32>().map_err(|_| IdError::InvalidNumber)?;
    if id == 0 { Err(IdError::Zero) } else { Ok(id) }
}

fn main() {
    for (line, input) in ["3", "-1", "0"].iter().enumerate() {
        match parse_id(input) {
            Ok(id) => println!("Line {}: book #{id}", line + 1),
            Err(error) => println!("Line {}: {}", line + 1, error.message()),
        }
    }
}
Text
Line 1: book #3
Line 2: use a whole-number ID
Line 3: ID must be positive

Now suppose you add a TooLarge variant and forget to update message. The program does not compile: error[E0004]: non-exhaustive patterns: &IdError::TooLarge not covered. That is the payoff of an enum over strings. Every place that interprets the error is pointed out to you.

What the question mark needs

? returns the error as the function's own error type. If the types differ, it needs a way to convert, and without one the code is rejected:

Rust
#[derive(Debug)]
enum IdError {
    InvalidNumber,
    Zero,
}

fn parse_id(text: &str) -> Result<u32, IdError> {
    let id = text.parse::<u32>()?;
    if id == 0 {
        return Err(IdError::Zero);
    }
    Ok(id)
}

The compiler reports error[E0277], says the question mark couldn't convert the error to IdError, and notes that IdError needs to implement From<ParseIntError>. You have two fixes. map_err converts at this one call site, which is what the queue does because it reads clearly. Implementing From<ParseIntError> for IdError converts automatically at every ?, which pays off when many functions share the same conversion. Either way, the caller sees only your enum.

One variant per thing the caller can fix

Add a variant when a person or the calling code would respond differently. "Not a number" and "zero" lead to different advice, so they are separate. Two internal causes with the same advice can share one variant.

Practice

Exercise

Your turn

Implement parse_pages(text: &str) -> Result<u32, PageError>. Return BadNumber for text that is not a valid u32 and OutsideRange for values outside 1 to 500, inclusive. Assert the results for 0, 500, 501 and unknown, then print Page checks passed.

Your working space Rust
#[derive(Debug, PartialEq, Eq)]
enum PageError {
    BadNumber,
    OutsideRange,
}

fn main() {
    // Parse and check 0, 500, 501 and unknown.
}
Hint 1: the idea

Convert the parsing error before propagating it. Range validation comes after a successful conversion, on the number itself.

Hint 2: a first step

Use text.parse::<u32>().map_err(|_| PageError::BadNumber)? to get the number, then test it with (1..=500).contains(&pages).

Worked solution
Run the solution Rust
#[derive(Debug, PartialEq, Eq)]
enum PageError {
    BadNumber,
    OutsideRange,
}

fn parse_pages(text: &str) -> Result<u32, PageError> {
    let pages = text.parse::<u32>().map_err(|_| PageError::BadNumber)?;
    if (1..=500).contains(&pages) {
        Ok(pages)
    } else {
        Err(PageError::OutsideRange)
    }
}

fn main() {
    assert_eq!(parse_pages("0"), Err(PageError::OutsideRange));
    assert_eq!(parse_pages("500"), Ok(500));
    assert_eq!(parse_pages("501"), Err(PageError::OutsideRange));
    assert_eq!(parse_pages("unknown"), Err(PageError::BadNumber));
    println!("Page checks passed");
}
Text
Page checks passed

Both 0 and 501 parse as integers, so only the range check catches them; 500 proves the upper bound is inclusive. Testing just inside and just outside each limit is the habit that catches an accidental 1..500. The next lesson applies the same idea to a field that may be missing entirely, where the standard library gives you an Option instead of a Result.

Was this article helpful?

Your response is saved on this device.