assemble_core/
error.rs

1//! An error with a payload
2
3use crate::project::ProjectError;
4use std::backtrace::Backtrace;
5use std::error::Error;
6use std::fmt::{Display, Formatter};
7use std::io;
8
9/// An payload with an error
10#[derive(Debug)]
11pub struct PayloadError<E> {
12    kind: E,
13    bt: Backtrace,
14}
15
16impl<E> PayloadError<E> {
17    /// Create a new payloaded error.
18    #[inline]
19    pub fn new<E2>(error: E2) -> Self
20    where
21        E2: Into<E>,
22    {
23        Self::with_backtrace(error, Backtrace::capture())
24    }
25
26    /// create a new payload error with a backtrace
27    pub fn with_backtrace<E2>(kind: E2, bt: Backtrace) -> Self
28    where
29        E2: Into<E>,
30    {
31        Self {
32            kind: kind.into(),
33            bt,
34        }
35    }
36
37    /// Gets the error kind
38    pub fn kind(&self) -> &E {
39        &self.kind
40    }
41
42    /// Gets the backtrace
43    pub fn backtrace(&self) -> &Backtrace {
44        &self.bt
45    }
46
47    /// Convert the error type
48    pub fn into<T>(self) -> PayloadError<T>
49    where
50        E: Into<T>,
51    {
52        PayloadError {
53            kind: self.kind.into(),
54            bt: self.bt,
55        }
56    }
57
58    /// Unwraps the payloaded error
59    pub fn into_inner(self) -> E {
60        self.kind
61    }
62}
63
64impl<E> From<E> for PayloadError<E> {
65    fn from(e: E) -> Self {
66        Self::new(e)
67    }
68}
69
70impl<E: Display> Display for PayloadError<E> {
71    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
72        write!(f, "{}", self.kind)
73    }
74}
75
76impl<E: Error> Error for PayloadError<E> {}
77
78impl<E> AsRef<E> for PayloadError<E> {
79    fn as_ref(&self) -> &E {
80        &self.kind
81    }
82}
83
84/// A result with a pay-loaded error
85pub type Result<T, E> = std::result::Result<T, PayloadError<E>>;
86
87impl From<io::Error> for PayloadError<ProjectError> {
88    fn from(e: io::Error) -> Self {
89        PayloadError::new(e)
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use crate::error::PayloadError;
96
97    #[test]
98    fn create_payload() {
99        let res = PayloadError::<()>::new(());
100        let bt = res.backtrace();
101        println!("{:?}", bt);
102    }
103}