Skip to main content

Attach

Trait Attach 

Source
pub trait Attach<Wrapper>: Sized {
    // Required method
    fn attach_location(self, location: Location) -> Wrapper;

    // Provided method
    fn attach(self) -> Wrapper { ... }
}
Expand description

Record error propagation locations for detailed backtraces.

The Attach trait provides the .attach() method which records where an error was propagated through your code, creating a complete call chain.

§Basic Usage

Use .attach() when propagating errors with ?:

use std::io;

use error2::prelude::*;

#[derive(Debug, Error2)]
#[error2(display("io error"))]
struct IoError {
    source: io::Error,
    backtrace: Backtrace,
}

fn inner() -> Result<String, IoError> {
    std::fs::read_to_string("file.txt").context(IoError2)
}

fn outer() -> Result<String, IoError> {
    let result = inner().attach()?; // Records this location in backtrace
    Ok(result)
}

§Why Use Attach?

Without .attach(), the backtrace only shows where the error was created. With .attach(), it shows every point the error passed through.

use regex::Regex;

if let Err(e) = outer() {
    let msg = e.backtrace().error_message();

    // Full error format with multiple locations:
    // IoError: io error
    //     at /path/to/file.rs:39:14
    //     at /path/to/file.rs:42:13
    // std::io::error::Error: file not found

    let re = Regex::new(concat!(
        r"(?s)^.+IoError: io error",
        r"\n    at .+\.rs:\d+:\d+",
        r"\n    at .+\.rs:\d+:\d+",
        r"\nstd::io::error::Error: file not found$",
    ))
    .unwrap();
    assert!(re.is_match(msg.as_ref()));
}

Required Methods§

Source

fn attach_location(self, location: Location) -> Wrapper

Records an explicit location (rarely needed).

Provided Methods§

Source

fn attach(self) -> Wrapper

Records the caller’s location in the error’s backtrace.

Uses #[track_caller] to automatically capture location.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T, E: Error2> Attach<Result<T, E>> for Result<T, E>

Source§

fn attach_location(self, location: Location) -> Self

Implementors§

Source§

impl<E: Error2> Attach<E> for E

Source§

impl<T, W> Attach<AttachIter<T, W>> for T
where T: Iterator, T::Item: Attach<W>,