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
#[macro_use]
extern crate serde_derive;

use std::fmt;

#[derive(Debug, Serialize, Deserialize)]
pub enum StrictApiResponse<T> {
    #[serde(rename = "success")]
    Success(T),
    #[serde(rename = "error")]
    Error(String),
}

impl<T> StrictApiResponse<T> {
    pub fn success(self) -> Result<T, ApiError> {
        match self {
            StrictApiResponse::Success(x) => Ok(x),
            StrictApiResponse::Error(err) => Err(ApiError(err)),
        }
    }
}

#[derive(Debug)]
pub struct ApiError(String);

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "api error: {:?}", self.0)
    }
}

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

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}