Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

The std::error module

Reference for Rust std::error: the Error trait, source chains, Box<dyn Error>, downcasting and writing custom error types that work with the ? operator.

std::error contains a single central item: the Error trait. A type that implements Error says "I am an error value": it can be printed for users (Display), shown to developers (Debug), and optionally point at the lower-level error that caused it through source(). Because the trait is an object-safe standard contract, you can store any error as Box<dyn Error> and pass it around without naming its type.

Implementing Error only requires that the type already implements Debug and Display; every method of the trait has a default. The ? operator uses From to convert errors, and the standard library provides From<E: Error> for Box<dyn Error> as well as From<&str> and From<String>.

Rust
use std::error::Error;

fn run() -> Result<(), Box<dyn Error>> {
    let n: i32 = "42".parse()?;
    println!("{n}");
    Ok(())
}

Try it

Rust A custom error with a source

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 Box dyn Error and downcasting

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
pub trait Error: Debug + Display {
    fn source(&self) -> Option<&(dyn Error + 'static)> { None }
    fn description(&self) -> &str { ... }   // deprecated
    fn cause(&self) -> Option<&dyn Error> { ... } // deprecated
}
Item Description
source() The underlying error, if any. Walk the chain by calling it repeatedly.
description(), cause() Deprecated; implement Display and source instead.
dyn Error methods is::<T>(), downcast_ref::<T>(), downcast_mut::<T>().
Box<dyn Error> downcast::<T>() returns Result<Box<T>, Box<dyn Error>>.
Box<dyn Error + Send + Sync> The thread-safe variant; also converts from &str and String.

Usage notes

  • Display is for people, Debug for developers. Keep Display messages short and lower case without a trailing period; they are often embedded in longer messages.
  • Do not repeat the source in Display. Return it from source() and let the reporter print the chain.
  • Box<dyn Error> is great for binaries and quick scripts, but libraries should return a concrete error type so callers can match on it.
  • main can return Result<(), Box<dyn Error>>; an Err is printed with Debug and the process exits with code 1.
  • Downcasting needs 'static. Errors that borrow data cannot be downcast.
  • Error lives in core too (since Rust 1.81), so no_std crates can implement it.
  • Send + Sync: use Box<dyn Error + Send + Sync> when errors cross threads, for example from thread::spawn results.
  • ? needs From: converting a specific error into Box<dyn Error> works for any E: Error, but Box<dyn Error> itself does not implement Error.