std-method

Error::source — preserve causes

Wrap a lower-level failure with information about the operation that failed, then expose the original error as a source. The borrowed cause is tied to the borrow of self; the object bound does not require the borrow itself to last forever. Expected stdout (not executed): invalid inventory quantity has source: true Common mistake: Replacing the original error with a message and losing its cause.

Formal Syntax & Structure

rust syntaxrust
fn source(&self) -> Option<&(dyn Error + 'static)>

Working Example

Example Snippetrust
use std::{error::Error, fmt, num::ParseIntError};#[derive(Debug)]struct LoadError(ParseIntError);impl fmt::Display for LoadError {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "invalid inventory quantity") }}impl Error for LoadError {    fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.0) }}impl From<ParseIntError> for LoadError {    fn from(e: ParseIntError) -> Self { Self(e) }}fn read_qty(s: &str) -> Result<u32, LoadError> { Ok(s.parse::<u32>()?) }fn main() {    let e = read_qty("bad").unwrap_err();    println!("{e}");    println!("has source: {}", e.source().is_some());}
Rust Reference