Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 132 ยท Error Handling

Custom Error Types

Build your own Rust error types: error enums, Display and std::error::Error, source() chains, From for ?, Box<dyn Error>, plus thiserror and anyhow explained.

Returning Result<T, String> is the quickest way to get started with errors, and it is fine for a ten-line script. It stops being fine the moment a caller wants to react to the failure. Is this a "file not found" I can create, or a "permission denied" I must report? Is the user's input wrong, or is the network down? With a String the only option is to search the text for keywords, which breaks the first time somebody edits a message.

A custom error type solves that. It is an ordinary enum or struct of your own that says exactly what can go wrong, carries the relevant data, prints a good message, and plays nicely with ?. This lesson builds one from scratch, one step at a time: the enum, the Display implementation, the std::error::Error trait, From conversions, error chains with source(), and the type-erased Box<dyn Error>. At the end you will see what the popular thiserror and anyhow crates do, and write runnable versions of the same ideas by hand. The strategic question of when to use which approach is the topic of error handling design.

Step 1: an enum of things that can go wrong

Each variant is one kind of failure, and it can carry whatever data helps the caller. Because it is an enum, callers can match on it and the compiler checks that every case is handled.

Rust An error enum you can match on

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice what the caller gained: it can compute the shortfall, because the error carries the numbers, and the final Err(other) arm shows how you can handle some variants specially and the rest generically. #[derive(Debug)] is needed because almost everything that handles errors (including unwrap, expect and main's error report) prints them with {:?}.

Step 2: Display for humans

Debug output is for developers. Something that reaches a user or a log needs a clean sentence, which is the job of the Display trait. By convention an error message starts with a lowercase letter, has no trailing period, and does not include the message of its cause (that is the job of source(), below).

Rust Implementing Display for an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Step 3: the Error trait

std::error::Error is the standard trait that says "this type is an error". It has no required methods. You implement it with an empty body, and you get a place to hang source() later. It requires that the type implements both Debug and Display, which is why those came first.

Rust
impl std::error::Error for WithdrawError {}

Why bother, when Display and Debug already exist? Because Error is the common interface that the rest of the ecosystem is written against: Box<dyn Error>, ? conversion into boxed errors, error-reporting libraries, test helpers and main's return type all expect it. If you forget Display, rustc tells you right away:

Rust Error without Display (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc stops with E0277 ("Oops doesn't implement std::fmt::Display"), pointing at the impl Error line, and adds a note that the missing trait is required by a bound in std::error::Error, because Display is a supertrait of Error. The fix is to implement Display for Oops, as in the previous step.

Step 4: From, so that ? just works

An error type usually wraps other errors from lower layers. Implement From<LowerError> for it and ? will convert for you, as you saw in the ? operator. It is customary to keep the original error inside the variant, so no information is lost:

Rust Wrapping lower-level errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This one uses a map_err closure rather than a From implementation, on purpose: the Parse variant needs the key, which From cannot know. A plain From<ParseIntError> is for the case where the source error alone says enough. Use whichever fits; both work with ?.

Step 5: source() and error chains

Real failures are stacked: "could not load the profile" because "could not read the config file" because "permission denied". The Error::source method lets each layer hand back the error that caused it, so a reporter can print the whole chain. The golden rule is that each error prints only its own message; the reporter walks the chain. If every layer also included its cause's text you would see the same sentence three times.

Rust Walking an error chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The report function accepts &dyn Error, so it works for any error type. That is the payoff of implementing the trait.

Box and downcasting

Box<dyn Error> is a pointer to any value that implements Error, with the concrete type erased. It is the easiest return type, and ? and .into() convert everything into it. The cost is that callers can no longer match on variants. If they really must find out what is inside, downcast_ref::<T>() asks "is it this type?" at run time.

Rust Downcasting a boxed error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Downcasting works, but if you find yourself writing a ladder of downcast_ref calls, you have outgrown Box<dyn Error> and want an enum instead.

A good default: library or reusable module? Use your own enum. Binary crate where errors mostly go to a log or the terminal? Box<dyn Error> (or anyhow) is fine. The next lesson expands on this.

What thiserror and anyhow do (read-only)

Writing Display, Error and From by hand is mechanical, and two crates from crates.io remove the boilerplate. Our editor runs single files with only the standard library, so the next snippets are read-only (they need a Cargo.toml with thiserror = "2" and anyhow = "1"):

Rust
// Read-only: needs the thiserror crate.
use thiserror::Error;

#[derive(Debug, Error)]
enum ConfigError {
    #[error("setting {key:?} is missing")]
    Missing { key: String },

    #[error("setting {key:?} is not a number"r")]
    Parse {
        key: String,
        #[source]
        source: std::num::ParseIntError,
    },

    #[error("
    Parse {
        key: String,
        #[source]
        source: std::num::ParseIntError,
    },

    #[error("could not read the file")]
    Io(#[from] std::io::Error),
}

The derive generates the Display implementation from the #[error("...")] text, the Error implementation including source() (from the #[source] field), and a From<std::io::Error> from #[from]. It is a pure convenience: the code it generates is what you wrote by hand above, and it adds no run-time cost. It is aimed at libraries, which want precise error enums.

Rust
// Read-only: needs the anyhow crate.
use anyhow::{Context, Result};

fn load(path: &str) -> Result<String> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("could not read {path}"))?;
    Ok(text)
}

anyhow::Error is essentially an improved Box<dyn Error>: it accepts any error through ?, adds a .context(...) method that stacks a message on top, prints the whole chain when you format it with {:#} or {:?}, and can capture a backtrace. It is aimed at applications, where errors are reported rather than matched.

Hand-written stand-ins you can run

You do not need the crates to get the same shape. Here is a tiny version of the anyhow idea, a context method added to every Result through an extension trait, which wraps the original error in a message layer:

Rust A hand-written context method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

That is about 30 lines for the core of what anyhow::Context does. Real anyhow adds a smart single-pointer representation, backtraces and nicer formatting, so use the crate in production, but knowing how it works makes its behavior unsurprising.

Design checklist

  • Name the type after the domain (ConfigError, ParseError), not after the mechanism (MyError).
  • Messages: lowercase start, no trailing period, no cause text duplicated. Callers add context when they print the chain.
  • Keep the original cause as a field and return it from source().
  • Implement From only where the conversion is obvious; use map_err where extra data (a key, a file name) must be attached.
  • Do not expose another crate's error type in your public API unless you mean to promise it forever.
  • Consider #[non_exhaustive] on public error enums so adding a variant later is not a breaking change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which traits must a type implement before you can implement std::error::Error for it?

    Error has Debug and Display as supertraits, so both must be implemented first.
  2. 2. What is Error::source for?

    source links errors into a chain, so a reporter can print each layer's message in turn.
  3. 3. What is the main drawback of Box<dyn Error> as a return type for a library?

    The concrete type is erased, so callers must use downcasting instead of a match. Libraries usually expose an enum.
  4. 4. Why implement From<ParseIntError> for MyError?

    ? calls From::from on the error, so the From implementation is what lets it convert.
  5. 5. What does #[derive(thiserror::Error)] with #[error("...")] generate?

    The derive writes the same boilerplate you write by hand, with no extra run-time cost.

Summary

  • A custom error is an enum or struct that says exactly what can go wrong and carries the data callers need.
  • Implement Debug (derive), Display (human message) and std::error::Error (usually an empty impl, plus source() when you wrap a cause).
  • From<Lower> for MyError lets ? convert errors automatically; use map_err when you must attach extra data.
  • Each error prints only its own message; a reporter walks source() to print the chain.
  • Box<dyn Error> accepts anything but hides the type; downcast_ref is the escape hatch. Prefer enums for libraries.
  • thiserror generates the boilerplate for enums; anyhow is a convenient Box<dyn Error> with context for applications. Both are read-only here, with runnable hand-written equivalents above.

Next: Error Handling Design