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
use reqwest::Error as ExternRequestError;
use std::error::Error as StdError;
use std::fmt;

#[derive(Debug)]
pub struct Error {
    pub kind: ErrorKind,
    pub source: Option<Box<dyn StdError>>,
    pub response: Option<String>,
}

#[derive(Debug)]
pub enum ErrorKind {
    /// HTTP client error (4xx). Caused by invalid request.
    /// See `response` field of `Error` for detail.
    ClientError,

    /// HTTP server error (5xx). Caused by server invernal error.
    ServerError,

    /// Unexpected response format causing serialization error.
    SerializeError,

    /// Other error from `reqwest` like transmission error.
    RequestError,
}

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

pub type Result<T> = ::std::result::Result<T, Error>;

impl StdError for Error {
    // TODO: fn source(&self) -> Option<&(dyn StdError + 'static)>;
}

impl From<ExternRequestError> for Error {
    fn from(e: ExternRequestError) -> Self {
        use self::ErrorKind::*;

        let kind = if e.is_client_error() {
            ClientError
        } else if e.is_server_error() {
            ServerError
        } else if e.is_serialization() {
            SerializeError
        } else {
            RequestError
        };
        Error {
            kind,
            source: Some(Box::new(e)),
            response: None,
        }
    }
}