1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ServerOtherBodyError {
    pub status_code: u16,
    pub status_message: String,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ServerValidationBodyError {
    pub errors: Vec<String>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ServerBodyError {
    Other(ServerOtherBodyError),
    Validation(ServerValidationBodyError),
}

impl From<ServerOtherBodyError> for ServerBodyError {
    fn from(inner: ServerOtherBodyError) -> Self {
        Self::Other(inner)
    }
}

impl From<ServerValidationBodyError> for ServerBodyError {
    fn from(inner: ServerValidationBodyError) -> Self {
        Self::Validation(inner)
    }
}

impl ServerBodyError {
    pub fn as_other_error(&self) -> Option<&ServerOtherBodyError> {
        match self {
            Self::Other(inner) => Some(inner),
            _ => None,
        }
    }

    pub fn as_validation_error(&self) -> Option<&ServerValidationBodyError> {
        match self {
            Self::Validation(inner) => Some(inner),
            _ => None,
        }
    }
}

#[derive(Debug)]
pub struct ServerError {
    pub code: u16,
    pub body: ServerBodyError,
}

#[cfg(feature = "commands")]
#[derive(Debug)]
pub enum Error {
    Reqwest(reqwest::Error),
    Server(ServerError),
}

#[cfg(feature = "commands")]
impl Error {
    pub fn as_reqwest_error(&self) -> Option<&reqwest::Error> {
        match self {
            Self::Reqwest(inner) => Some(inner),
            _ => None,
        }
    }

    pub fn is_reqwest_error(&self) -> bool {
        matches!(self, Self::Reqwest(_))
    }

    pub fn as_server_error(&self) -> Option<&ServerError> {
        match self {
            Self::Server(inner) => Some(inner),
            _ => None,
        }
    }

    pub fn is_server_error(&self) -> bool {
        matches!(self, Self::Server(_))
    }
}

#[cfg(feature = "commands")]
impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Self::Reqwest(err)
    }
}

#[cfg(feature = "commands")]
impl From<(reqwest::StatusCode, ServerBodyError)> for Error {
    fn from((code, body): (reqwest::StatusCode, ServerBodyError)) -> Self {
        Self::Server(ServerError {
            code: code.as_u16(),
            body,
        })
    }
}