1use std::{any::type_name_of_val, error::Error, fmt::{Debug, Display, Formatter}};
2
3
4pub type DceResult<T> = Result<T, DceError>;
5pub type DceVoid = DceResult<()>;
6pub const OK_VOID: DceVoid = Ok(());
7
8pub const SERVICE_UNAVAILABLE: isize = 503;
9pub const SERVICE_UNAVAILABLE_MESSAGE: &str = "Service Unavailable";
10
11#[derive(Debug)]
12pub enum DceFaultBody {
13 Message(String),
14 Error(&'static str, Box<dyn Error + Send>),
15}
16
17impl Display for DceFaultBody {
18 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
19 match self {
20 Self::Message(msg) => f.write_fmt(format_args!("{}", msg)),
21 Self::Error(ty, err) => f.write_fmt(format_args!("[{}] {}", ty, err)),
22 }
23 }
24}
25
26#[derive(Debug)]
27pub struct DceError {
28 pub public: bool,
29 pub code: isize,
30 pub body: DceFaultBody,
31}
32
33impl DceError {
34 pub fn msg<T: ToString>(public: bool, code: isize, message: T) -> Self {
35 DceError { public, code, body: DceFaultBody::Message(message.to_string()) }
36 }
37
38 pub fn pub_msg<T: ToString>(code: isize, message: T) -> Self {
39 Self::msg(true, code, message)
40 }
41
42 pub fn pub_msg0<T: ToString>(message: T) -> Self {
43 Self::msg(true, -1, message)
44 }
45
46 pub fn priv_msg<T: ToString>(code: isize, message: T) -> Self {
47 Self::msg(false, code, message)
48 }
49
50 pub fn priv_msg0<T: ToString>(message: T) -> Self {
51 Self::msg(false, -1, message)
52 }
53
54 pub fn err<T: Error + Send + 'static>(public: bool, code: isize, error: T) -> Self {
55 DceError { public, code, body: DceFaultBody::Error(type_name_of_val(&error), Box::new(error)) }
56 }
57
58 pub fn pub_err<T: Error + Send + 'static>(code: isize, error: T) -> Self {
59 Self::err(true, code, error)
60 }
61
62 pub fn pub_err0<T: Error + Send + 'static>(error: T) -> Self {
63 Self::err(true, -1, error)
64 }
65
66 pub fn priv_err<T: Error + Send + 'static>(code: isize, error: T) -> Self {
67 Self::err(false, code, error)
68 }
69
70 pub fn priv_err0<T: Error + Send + 'static>(error: T) -> Self {
71 Self::err(false, -1, error)
72 }
73}
74
75impl <T: Error + Send + 'static> From<T> for DceError {
76 fn from(value: T) -> Self {
77 DceError::err(false, -1, value)
78 }
79}
80
81impl Display for DceError {
82 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
83 let Self{public, code, body} = self;
84 let flag = if *public { "PUB" } else { "PRIV" };
85 f.write_fmt(format_args!("[{}] {}: {}", flag, code, body))
86 }
87}