Skip to content

Preserve an Error’s Underlying Cause

The Course
•
28 min study

When a low-level operation fails inside a library, two kinds of information matter. The caller needs to know which task failed, such as "could not import quantity", because that is what it asked for. Someone debugging also wants the precise cause underneath, such as "invalid digit found in string". Returning only the low-level ParseIntError loses the first; replacing it with a string loses the second. The standard pattern keeps both: wrap the cause inside an operation-specific error type and expose it through Error::source.

Two trait implementations make that pattern pleasant. From<ParseIntError> for ImportError lets ? convert the inner error automatically, so the happy path stays a single expression. source returns Option<&(dyn Error + 'static)>, which lets any caller follow the chain of causes without knowing the concrete types. The returned reference borrows the error stored inside self. The 'static bound is about the concrete error type: it promises that type holds no short-lived borrowed data. It does not make this particular reference live forever.

Predict and run

What does the outer message add? Is the parse error still available?

Predict, then run Rust
use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct ImportError(std::num::ParseIntError);

impl fmt::Display for ImportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("could not import quantity")
    }
}

impl Error for ImportError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.0)
    }
}

impl From<std::num::ParseIntError> for ImportError {
    fn from(error: std::num::ParseIntError) -> Self { Self(error) }
}

fn quantity(text: &str) -> Result<u32, ImportError> {
    Ok(text.parse()?)
}
fn main() {
    let error = quantity("later").unwrap_err();
    println!("{error}");
    println!("Has source: {}", error.source().is_some());
}
Check your prediction
Text
could not import quantity
Has source: true

The Display text names the task, and the cause is still stored, just not printed. Change "later" to "12" and print quantity("12"): no error value is built at all, because From runs only on the failure path. Then print {:?} of error.source() and you will see the full ParseIntError with its kind.

Remove the From implementation and the ? stops compiling:

Rust
fn quantity(text: &str) -> Result<u32, ImportError> {
    Ok(text.parse::<u32>()?)
}

The compiler reports error[E0277]: `?` couldn't convert the error to `ImportError` . The question mark is not magic: it calls From::from on the error, and that conversion must exist.

Walk the chain, don't duplicate it

Errors often nest more than once. A loader that failed on batch 3 might wrap the import error, which wraps the parse error. A reporter can then print every level by following source until it returns None.

Walk the source chain Rust
use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct ImportError(std::num::ParseIntError);

impl fmt::Display for ImportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("could not import quantity")
    }
}

impl Error for ImportError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.0)
    }
}

#[derive(Debug)]
struct LoadError { batch: u32, cause: ImportError }

impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "could not load batch {}", self.batch)
    }
}

impl Error for LoadError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.cause)
    }
}

fn main() {
    let parse = "later".parse::<u32>().unwrap_err();
    let error = LoadError { batch: 3, cause: ImportError(parse) };
    println!("error: {error}");
    let mut current = error.source();
    while let Some(cause) = current {
        println!("caused by: {cause}");
        current = cause.source();
    }
}
Text
error: could not load batch 3
caused by: could not import quantity
caused by: invalid digit found in string

Each Display describes only its own level. That is a deliberate convention: if ImportError printed could not import quantity: invalid digit found in string, a reporter walking the chain would show the parse message twice. Pick one place for the cause to appear. Exposing it through source is the better choice, because the caller decides how much detail to show.

Recover the concrete cause

Because the trait object is 'static, a caller can ask whether a source is a specific type with downcast_ref. Downcasting relies on TypeId, which only exists for types without borrowed lifetimes, so this is the practical reason behind the bound.

Downcast a source to its concrete type Rust
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
struct ImportError(ParseIntError);

impl fmt::Display for ImportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("could not import quantity")
    }
}

impl Error for ImportError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.0)
    }
}

fn main() {
    for text in ["later", ""] {
        let error = ImportError(text.parse::<u32>().unwrap_err());
        let kind = error.source()
            .and_then(|cause| cause.downcast_ref::<ParseIntError>())
            .map(|cause| cause.kind().clone());
        println!("{text:?}: {kind:?}");
    }
}
Text
"later": Some(InvalidDigit)
"": Some(Empty)

A caller could use this to say "the quantity was blank" instead of a generic message, without the library adding a variant for every case.

Typed enum or boxed error?

A library usually exposes its own error enum, so callers can match on variants and the set of failures is documented by the type. An application's top level often uses Box<dyn Error>, because it only reports errors and never branches on them. The source chain works the same way in both.

Practice

Exercise

Your turn

Define enum ConfigError { Missing, Invalid(ParseIntError) } with Display messages missing limit and invalid limit. Implement Error so Missing has no source and Invalid exposes its parse error. Build one of each, using "x".parse::<u32>() for the invalid case, and print each message with whether it has a source. For the invalid case, also print the cause on a caused by: line.

Your working space Rust
fn main() {
    // Define ConfigError and its Display and Error implementations.
}
Hint 1: the idea

Only the variant carrying an error can return a source reference. The other returns None.

Hint 2: a first step

match self inside source, return None for Self::Missing, and Some(error) for Self::Invalid(error). The reference coerces to &(dyn Error + 'static) automatically.

Worked solution
Run the solution Rust
use std::error::Error;
use std::fmt;

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

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing => f.write_str("missing limit"),
            Self::Invalid(_) => f.write_str("invalid limit"),
        }
    }
}
impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Missing => None,
            Self::Invalid(error) => Some(error),
        }
    }
}

fn main() {
    let invalid = ConfigError::Invalid("x".parse::<u32>().unwrap_err());
    for error in [ConfigError::Missing, invalid] {
        println!("{error} (source: {})", error.source().is_some());
        if let Some(cause) = error.source() {
            println!("caused by: {cause}");
        }
    }
}
Text
missing limit (source: false)
invalid limit (source: true)
caused by: invalid digit found in string

Missing is a complete explanation by itself, so it has no source, while Invalid keeps its cause as structured data. The project's ParseError uses the same shape: its Validation variant exposes a ValidationError as its source, and its other variants return None.

Was this article helpful?

Your response is saved on this device.