Skip to content
Theory · Errors · lesson 8 of 8

Your own error type

A courier's note can be handwritten: "nobody home", "wrong address". A person will read it, but the sorting machine at the warehouse will not. That is why a delivery service has a form with ready-made items, where the courier ticks a box. From the tick, the machine knows at once where to send the parcel next.

A string error is a handwritten note. Look at what the calling code sees:

Rust
fn parse_age(s: &str) -> Result<u32, String> {
    match s.parse::<u32>() {
        Ok(age) if age > 150 => Err(format!("too old: {age}")),
        Ok(age) => Ok(age),
        Err(e) => Err(format!("not a number: {e}")),
    }
}

fn main() {
    println!("{:?}", parse_age("x")); // Err("not a number: invalid digit found in string")
    println!("{:?}", parse_age("200")); // Err("too old: 200")
}

The error has two causes, and each deserves its own reaction: for letters, ask for digits; for 200, ask about the birth year. But both causes arrive as strings. To tell them apart, the calling code would have to compare text, and a typo in one letter would silently break the check.

An enum of causes

The tick-box form in Rust is an enum: each variant is one cause of the error, and a variant can store details.

Rust
#[derive(Debug)]
enum AgeError {
    NotNumber(std::num::ParseIntError),
    TooOld(u32),
}

impl std::fmt::Display for AgeError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            AgeError::NotNumber(e) => write!(f, "not a number: {e}"),
            AgeError::TooOld(age) => write!(f, "too old: {age}"),
        }
    }
}

Let's walk through the example part by part:

  1. NotNumber stores the original parse error. std::num::ParseIntError is the full name of its type, so no use line is needed.
  2. TooOld stores the age that failed the check.
  3. #[derive(Debug)] gives debug printing with {:?}.
  4. impl std::fmt::Display for AgeError teaches the type to print with {}, as text for a person. As you remember, the compiler does not derive the Display trait, so you implement it by hand.
  5. The form impl Trait for Type gives a type a trait: inside go the methods the trait requires, here only one, fmt. Traits get a closer look later; for now take this form as a template.
  6. Inside fmt there is a match over the variants, and the write! macro builds text by the rules of format! and writes it into f. write! returns std::fmt::Result, a special Result for printing, and that value becomes the result of fmt, so you do not write Ok.

Now println!("{e}") for AgeError::TooOld(200) prints too old: 200, and the calling code tells the causes apart with patterns: the arm Err(AgeError::TooOld(age)) catches only an age that is too large.

Here the form analogy falls short: on a form you can tick several items at once. An enum value is always exactly one variant.

? and the From trait

You want to write parse_age briefly, with ?. But parse returns a ParseIntError, while the function promises an AgeError. On Err, the ? operator does not return the error as it is: first it tries to turn it into the function's error type. That takes the From trait: it describes how to get your type from someone else's.

Rust
impl From<std::num::ParseIntError> for AgeError {
    fn from(e: std::num::ParseIntError) -> Self {
        AgeError::NotNumber(e)
    }
}

fn parse_age(s: &str) -> Result<u32, AgeError> {
    let age = s.parse::<u32>()?;
    if age > 150 {
        return Err(AgeError::TooOld(age));
    }
    Ok(age)
}

println!("{:?}", parse_age("x")); // Err(NotNumber(ParseIntError { kind: InvalidDigit }))
  1. impl From<…> for AgeError says: "an AgeError can be made from a ParseIntError".
  2. The from method takes the foreign error and puts it into the NotNumber variant.
  3. On an error, s.parse::<u32>()? calls this from and returns Err(AgeError::NotNumber(e)).
  4. The output shows exactly that: the original error sits inside NotNumber.

When the error type of the expression and of the function are the same, as in the previous lesson, the conversion changes nothing.

Interviewers like to ask this: "How would you design your own errors?" An enum with a variant for each cause, Display for people, and From so that ? works.

Any error: Box<dyn Error>

Sometimes you do not need to tell causes apart: in main or in a small program, showing the error is enough. Then you write fn main() -> Result<(), Box<dyn Error>>, after adding the line use std::error::Error;. How Box<dyn Error> works does not matter yet: read it as a whole as "any error".

? turns any standard library error into a Box<dyn Error> without a From of yours. Your own type gets in after one line: impl std::error::Error for AgeError {}. It works because AgeError already has Debug and Display.

The price of convenience: you can no longer take a variant out of a Box<dyn Error> with a pattern. So you write your own enum for code that others call, and use Box<dyn Error> in main and short programs.

Common mistake

You wrote your own error type but forgot From:

Rust
enum PortError {
    Bad(std::num::ParseIntError),
}

fn parse_port(s: &str) -> Result<u16, PortError> {
    let port = s.parse::<u16>()?; // ✗
    Ok(port)
}
TEXT
error[E0277]: `?` couldn't convert the error to `PortError`

The program does not compile. There is a variant for the parse error, but ? does not know how to turn a ParseIntError into a PortError. The compiler does not pick a variant by its field type. The fix is impl From<std::num::ParseIntError> for PortError, as for AgeError.

Key points

  • Your own error type is an enum: a variant for each cause, with the details stored in the variant.
  • You write Display by hand so the error prints with {} as text for a person.
  • ? converts the error through From; without impl From you get E0277.
  • Box<dyn Error> accepts any error, but you can no longer take a variant out of it with a pattern.