gufo_common/
error.rs

1/// Type that allows to return data with the error
2///
3/// This is useful since commands like `new()` will take ownership of the data.
4/// Using this as error type allows to continue using the data afterward.
5pub struct ErrorWithData<E: std::error::Error> {
6    err: E,
7    data: Vec<u8>,
8}
9
10impl<E: std::error::Error> ErrorWithData<E> {
11    pub fn new(err: E, data: Vec<u8>) -> Self {
12        Self { err, data }
13    }
14
15    pub fn err(&self) -> &E {
16        &self.err
17    }
18
19    pub fn into_inner(self) -> Vec<u8> {
20        self.data
21    }
22
23    pub fn map_err<F: std::error::Error>(self, op: impl FnOnce(E) -> F) -> ErrorWithData<F> {
24        let err = op(self.err);
25        ErrorWithData {
26            err,
27            data: self.data,
28        }
29    }
30}
31
32impl<E: std::error::Error> std::fmt::Debug for ErrorWithData<E> {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("ErrorWithData")
35            .field("err", &self.err)
36            .field("data", &format!("{} bytes", self.data.len()))
37            .finish()
38    }
39}
40
41impl<E: std::error::Error> std::fmt::Display for ErrorWithData<E> {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "{}", self.err)
44    }
45}
46
47impl<E: std::error::Error> std::error::Error for ErrorWithData<E> {}