whisky_common/errors/
mod.rs

1use std::fmt;
2
3#[derive(Clone)]
4pub struct WError {
5    traces: Vec<String>,
6}
7
8impl WError {
9    pub fn new(error_origin: &str, err: &str) -> Self {
10        let msg = format!("[Error - {}]: {}", error_origin, err);
11        WError { traces: vec![msg] }
12    }
13
14    pub fn add_trace(&mut self, trace: &str) {
15        self.traces.push(trace.to_string());
16    }
17
18    pub fn from_opt(error_origin: &'static str, err: &'static str) -> impl FnOnce() -> WError {
19        move || WError::new(error_origin, err)
20    }
21
22    pub fn from_err<F>(error_origin: &'static str) -> impl FnOnce(F) -> WError
23    where
24        F: std::fmt::Debug + 'static,
25    {
26        move |err| {
27            if let Some(werror) = (&err as &dyn std::any::Any).downcast_ref::<WError>() {
28                let mut werror = werror.clone();
29                werror.add_trace(error_origin);
30                werror
31            } else {
32                WError::new(error_origin, &format!("{:?}", err))
33            }
34        }
35    }
36
37    pub fn add_err_trace(error_origin: &'static str) -> impl FnOnce(WError) -> WError {
38        move |mut werror| {
39            werror.add_trace(error_origin);
40            werror
41        }
42    }
43}
44
45// Implement the Display trait for WError
46impl fmt::Display for WError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "{}", self.traces.join("\n"))
49    }
50}
51
52// Implement the Debug trait for WError
53impl fmt::Debug for WError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(f, "{}", self.traces.join("\n"))
56    }
57}