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
#[derive(Debug)]
pub struct AgdbApiError {
    pub status: u16,
    pub description: String,
}

impl std::error::Error for AgdbApiError {}

impl std::fmt::Display for AgdbApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.status, self.description)
    }
}

#[cfg(feature = "reqwest")]
impl From<reqwest::Error> for AgdbApiError {
    fn from(error: reqwest::Error) -> Self {
        Self {
            status: error
                .status()
                .unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR)
                .as_u16(),
            description: error.to_string(),
        }
    }
}

impl From<serde_json::Error> for AgdbApiError {
    fn from(value: serde_json::Error) -> Self {
        Self {
            status: 0,
            description: value.to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn derived_from_debug() {
        format!(
            "{:?}",
            AgdbApiError {
                status: 0,
                description: "test".to_string(),
            }
        );
    }

    #[test]
    fn display() {
        assert_eq!(
            format!(
                "{}",
                AgdbApiError {
                    status: 0,
                    description: "test".to_string(),
                }
            ),
            "0: test"
        );
    }

    #[cfg(feature = "reqwest")]
    #[test]
    fn from_reqwest_error() {
        let error = reqwest::ClientBuilder::new()
            .user_agent("\0")
            .build()
            .unwrap_err();
        assert_eq!(
            AgdbApiError::from(error).description,
            "builder error: failed to parse header value"
        );
    }

    #[test]
    fn from_serde_json_eror() {
        let error = serde_json::from_str::<()>("").unwrap_err();
        assert_eq!(
            AgdbApiError::from(error).description,
            "EOF while parsing a value at line 1 column 0"
        );
    }
}