Error

The Error trait, source chains, and From conversions for ?, without repeating Option and Result basics.

std::error::Error is the standard-library trait for error types. It requires Debug and Display. The provided source method returns the underlying error, if any. This page is about implementing Error, chaining source, and converting error types so ? can change the Err type. It does not repeat the Option and Result page, which already covers unwrap, parse, and the basic return-type constraint of ?.

Third-party crates such as thiserror and anyhow are outside the scope of these pages. Box<dyn Error> is the standard-library way to erase an error type when you only need Display and source. When the failure comes from std::io::Error, compare kind() with ErrorKind rather than asserting the operating-system Display text.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Error::source, From, ?Implement Error and From so ? can convert a leaf error into an application error, then walk source() for the cause.
io::Error::new, io::Error::kind, Box<dyn Error>Build an io::Error with a known kind and message, and erase errors with Box<dyn Error> when a single return type is enough.

Implementing Error and From

A type can implement Error once it implements Debug and Display. Implement source when the error wraps another error, and return that inner value as a trait object. Implementing From<InnerError> for AppError lets ? convert an InnerError into AppError. The example below uses only error messages defined in the program, so the printed text does not depend on an operating-system string.

Error::source, From, ?

pub trait Error: Debug + Display {
    fn source(&self) -> Option<&(dyn Error + 'static)> { ... }
}
pub trait From<T>: Sized {
    fn from(value: T) -> Self;
}

Implement Error and From so ? can convert a leaf error into an application error, then walk source() for the cause.

ParameterDescription
valueFrom::from is what ? uses to convert the Err type of a callee into the Err type of the caller.

Returns: source returns Option<&(dyn Error + 'static)>. From::from returns the converted error. ? either yields the success value or returns early with the converted error.

  • The Option and Result page shows map_err and the requirement that the enclosing function return a compatible Result. This example relies on From instead of map_err.
  • Call source through the Error trait, which must be in scope: use std::error::Error.
  • description and cause on the Error trait are deprecated provided methods; new code should use Display and source.
rust
use std::error::Error;

#[derive(Debug)]
struct ParsePortError;

impl std::fmt::Display for ParsePortError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid port")
    }
}

impl Error for ParsePortError {}

#[derive(Debug)]
enum AppError {
    Parse(ParsePortError),
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AppError::Parse(err) => write!(f, "parse error: {err}"),
        }
    }
}

impl Error for AppError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            AppError::Parse(err) => Some(err),
        }
    }
}

impl From<ParsePortError> for AppError {
    fn from(value: ParsePortError) -> Self {
        AppError::Parse(value)
    }
}

fn load() -> Result<(), AppError> {
    Err(ParsePortError)?;
    Ok(())
}

fn main() {
    match load() {
        Err(err) => {
            println!("display={err}");
            println!("source={:?}", err.source().map(|s| s.to_string()));
        }
        Ok(()) => println!("unexpected ok"),
    }
}

Expected output

display=parse error: invalid port
source=Some("invalid port")

Related: Option and Result page, The ? operator

Official documentation →

io::ErrorKind and Box<dyn Error>

io::Error::new builds an error with a chosen ErrorKind and a message you control. kind() returns that discriminant, which is the portable check. The Display text in this example is the message passed to Error::new, not a host-specific OS string. Box<dyn Error> implements From for any Error + 'static type, so ? can erase ParsePortError or an io::Error into a single return type when you do not want a custom enum.

io::Error::new, io::Error::kind, Box<dyn Error>

pub fn new<E>(kind: ErrorKind, error: E) -> Error
    where E: Into<Box<dyn Error + Send + Sync>>
pub fn kind(&self) -> ErrorKind
// Result<T, Box<dyn Error>> can use ? on many standard error types

Build an io::Error with a known kind and message, and erase errors with Box<dyn Error> when a single return type is enough.

ParameterDescription
kindAn ErrorKind variant such as NotFound. The enum is marked non_exhaustive, so a match should have a wildcard arm in library code.
errorA message or error that becomes the Display text of the io::Error.

Returns: Error::new returns an io::Error. kind returns the ErrorKind. Box<dyn Error> is a trait object that still supports Display and source.

Errors and panics

  • ErrorKind::NotFound — Used here with a caller-supplied message, "missing config". A real fs failure can also have this kind; compare the kind, not the OS text.
  • The boxed example prints "invalid port", which is the Display of ParsePortError after it is converted with ?.
rust
use std::error::Error;
use std::io::{self, ErrorKind};

#[derive(Debug)]
struct ParsePortError;

impl std::fmt::Display for ParsePortError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid port")
    }
}

impl Error for ParsePortError {}

fn load_io() -> Result<(), io::Error> {
    Err(io::Error::new(ErrorKind::NotFound, "missing config"))?;
    Ok(())
}

fn boxed() -> Result<(), Box<dyn Error>> {
    Err(ParsePortError)?;
    Ok(())
}

fn main() {
    let err = load_io().unwrap_err();
    println!("io-kind={:?}", err.kind());
    println!("io-display={err}");
    match boxed() {
        Err(err) => println!("boxed={err}"),
        Ok(()) => println!("unexpected ok"),
    }
}

Expected output

io-kind=NotFound
io-display=missing config
boxed=invalid port

Official documentation →