Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Errors, Panics and Process

Writing a custom error type in Rust

How to write a custom Rust error type: an enum of failure kinds, Display, std::error::Error, source chains and From impls that make the ? operator work.

A custom error type gives callers something precise to match on and lets you attach exactly the data an error needs. The standard recipe has four parts: an enum (or struct) describing the failures, a Display impl with a human-readable message, an empty impl Error (optionally overriding source), and From impls that convert the underlying errors so the ? operator does the wrapping for you.

No crate is required. Libraries such as thiserror generate these impls with attributes, but they only write the code shown here.

Rust
#[derive(Debug)]
enum ConfigError {
    Missing(String),
    BadNumber(std::num::ParseIntError),
}

Try it

Rust An error enum with From and ?

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.

Rust From impls make ? convert automatically

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.

Syntax

Rust
use std::{error::Error, fmt};

#[derive(Debug)]
pub enum MyError { /* variants */ }

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { /* ... */ }
}
impl Error for MyError {
    fn source(&self) -> Option<&(dyn Error + 'static)> { None }
}
impl From<OtherError> for MyError {
    fn from(e: OtherError) -> Self { /* wrap */ }
}
Piece Why it is needed
Debug Error requires Debug + Display. Derive it.
Display The message shown to users; keep it lowercase and without a trailing period by convention.
Error Marks the type as an error and gives source() (the underlying cause) a place to live.
From<E> Lets ? convert E into your type. One impl per source error type.

Usage notes

  • Use an enum when callers should be able to match on the failure kind; use a struct (possibly with a private kind field) when you want to keep the option of changing the internals later.
  • Put data in variants (the key, the path, the offending value). A message-only variant forces callers to parse strings.
  • Report the cause either through source() or in the Display text, not both; otherwise error-reporting tools that walk the chain print it twice.
  • Mark public error enums #[non_exhaustive] if you may add variants without a breaking release.
  • Avoid impl From<E> for two sources that share the same type (two different io::Error situations, for example). Use map_err with a distinct variant instead.
  • Make the type Send + Sync + 'static (all fields must be), so it fits Box<dyn Error + Send + Sync> and works across threads.
  • A type alias such as type Result<T> = std::result::Result<T, MyError>; keeps signatures short.