Skip to main content

error2/
error2.rs

1use std::{convert::Infallible, error::Error};
2
3use crate::Backtrace;
4
5/// Core trait extending `std::error::Error` with backtrace support.
6///
7/// `Error2` provides methods to access and modify the error's backtrace,
8/// enabling detailed error propagation tracking across your application.
9///
10/// # Implementation
11///
12/// Typically implemented via `#[derive(Error2)]` macro:
13///
14/// ```
15/// use error2::prelude::*;
16///
17/// #[derive(Debug, Error2)]
18/// #[error2(display("configuration error"))]
19/// struct ConfigError {
20///     backtrace: Backtrace,
21/// }
22/// ```
23///
24/// The macro automatically generates the trait implementation and manages
25/// the backtrace field.
26///
27/// # Accessing Backtrace
28///
29/// Use the `.backtrace()` method to access error chain and locations:
30///
31/// ```
32/// # use error2::prelude::*;
33/// # use std::io;
34/// # #[derive(Debug, Error2)]
35/// # #[error2(display("test"))]
36/// # struct MyError { source: io::Error, backtrace: Backtrace }
37/// # fn do_something() -> Result<(), MyError> { Ok(()) }
38/// if let Err(e) = do_something() {
39///     println!("{}", e.backtrace().error_message());
40/// }
41/// ```
42///
43/// See [`Backtrace`] for details on accessing error information.
44pub trait Error2: Error {
45    /// Returns a reference to the error's backtrace.
46    ///
47    /// The backtrace contains the complete error chain and location information.
48    fn backtrace(&self) -> &Backtrace;
49
50    /// Returns a mutable reference to the error's backtrace.
51    ///
52    /// Used internally by the library to record error propagation locations.
53    fn backtrace_mut(&mut self) -> &mut Backtrace;
54}
55
56impl Error2 for Infallible {
57    fn backtrace(&self) -> &Backtrace {
58        match *self {}
59    }
60
61    fn backtrace_mut(&mut self) -> &mut Backtrace {
62        match *self {}
63    }
64}
65
66impl<T: Error2> Error2 for Box<T> {
67    #[inline]
68    fn backtrace(&self) -> &Backtrace {
69        self.as_ref().backtrace()
70    }
71
72    #[inline]
73    fn backtrace_mut(&mut self) -> &mut Backtrace {
74        self.as_mut().backtrace_mut()
75    }
76}