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§
Sourcefn attach_location(self, location: Location) -> Wrapper
fn attach_location(self, location: Location) -> Wrapper
Records an explicit location (rarely needed).
Provided Methods§
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.