dce_util/
mixed.rs

1use std::fmt::{Display, Formatter};
2
3pub type DceResult<T> = Result<T, DceErr>;
4
5#[derive(Debug)]
6pub enum DceErr {
7    /// openly error, will print in console and send to client
8    Openly(DceError),
9    Closed(DceError),
10}
11
12impl DceErr {
13    pub fn value(&self) -> &DceError {
14        match self {
15            DceErr::Openly(v) => v,
16            DceErr::Closed(v) => v,
17        }
18    }
19
20    pub fn openly<T: ToString>(code: isize, message: T) -> Self {
21        Self::Openly(DceError {code, message: message.to_string()})
22    }
23
24    pub fn closed<T: ToString>(code: isize, message: T) -> Self {
25        Self::Closed(DceError {code, message: message.to_string()})
26    }
27
28    pub fn openly0<T: ToString>(message: T) -> Self {
29        Self::Openly(DceError {code: 0, message: message.to_string()})
30    }
31
32    pub fn closed0<T: ToString>(message: T) -> Self {
33        Self::Closed(DceError {code: 0, message: message.to_string()})
34    }
35
36    pub fn none() -> Self {
37        Self::Closed(DceError {code: 0, message: "Need Some but got None".to_string()})
38    }
39
40    pub fn openly0_wrap<M: ToString, R>(message: M) -> Result<R, Self> {
41        Err(Self::Openly(DceError {code: 0, message: message.to_string()}))
42    }
43
44    pub fn closed0_wrap<M: ToString, R>(message: M) -> Result<R, Self> {
45        Err(Self::Closed(DceError {code: 0, message: message.to_string()}))
46    }
47
48    pub fn to_responsible(&self) -> String {
49        match self {
50            DceErr::Openly(e) => format!("{}: {}", e.code, e.message),
51            DceErr::Closed(_) => format!("{}: {}", SERVICE_UNAVAILABLE, SERVICE_UNAVAILABLE_MESSAGE),
52        }
53    }
54}
55
56#[derive(Debug)]
57pub struct DceError {
58    pub code: isize,
59    pub message: String,
60}
61
62
63impl Display for DceErr {
64    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65        let (code, message) = match self {
66            DceErr::Openly(DceError{code, message}) => (code, message),
67            DceErr::Closed(DceError{code, message}) => (code, message),
68        };
69        f.write_str(format!("{}: {}", code, message).as_str())
70    }
71}
72
73impl std::error::Error for DceErr {}
74
75pub const SERVICE_UNAVAILABLE: isize = 503;
76pub const SERVICE_UNAVAILABLE_MESSAGE: &str = "Service Unavailable";