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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
//! Client errors
use crate::jwt::errors::Error as JWTError;
use http::StatusCode;
use reqwest::Error as ReqwestError;
use serde::Deserialize;
use serde_json::error::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
use std::result::Result as StdResult;
use std::time::Duration;
use url::ParseError;

/// A standard result type capturing common errors for all GitHub operations
pub type Result<T> = StdResult<T, Error>;

#[derive(Debug)]
pub enum Error {
    /// Client side error returned for faulty requests
    Fault {
        code: StatusCode,
        error: ClientError,
    },
    /// Error kind returned when a credential's rate limit has been exhausted. Wait for the reset duration before issuing more requests
    RateLimit { reset: Duration },
    /// Serialization related errors
    Codec(SerdeError),
    /// HTTP client errors
    Reqwest(ReqwestError),
    /// Url format errors
    Url(ParseError),
    /// Network errors
    IO(IoError),
    /// JWT validation errors
    JWT(JWTError),
}

impl From<SerdeError> for Error {
    fn from(err: SerdeError) -> Self {
        Error::Codec(err)
    }
}

impl From<ReqwestError> for Error {
    fn from(err: ReqwestError) -> Self {
        Error::Reqwest(err)
    }
}

impl From<ParseError> for Error {
    fn from(err: ParseError) -> Self {
        Error::Url(err)
    }
}

impl From<IoError> for Error {
    fn from(err: IoError) -> Self {
        Error::IO(err)
    }
}

impl From<JWTError> for Error {
    fn from(err: JWTError) -> Self {
        Error::JWT(err)
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Codec(err) => Some(err),
            Error::Reqwest(err) => Some(err),
            Error::Url(err) => Some(err),
            Error::IO(err) => Some(err),
            Error::JWT(err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Fault { code, error } => write!(f, "{}: {}", code, error.message),
            Error::RateLimit { reset } => write!(
                f,
                "Rate limit exhausted. Will reset in {} seconds",
                reset.as_secs()
            ),
            Error::Codec(err) => write!(f, "{}", err),
            Error::Reqwest(err) => write!(f, "{}", err),
            Error::Url(err) => write!(f, "{}", err),
            Error::IO(err) => write!(f, "{}", err),
            Error::JWT(err) => write!(f, "{}", err),
        }
    }
}

// representations

#[derive(Debug, Deserialize, PartialEq)]
pub struct FieldErr {
    pub resource: String,
    pub field: Option<String>,
    pub code: String,
    pub message: Option<String>,
    pub documentation_url: Option<String>,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct ClientError {
    pub message: String,
    pub errors: Option<Vec<FieldErr>>,
    pub documentation_url: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::{ClientError, FieldErr};

    #[test]
    fn deserialize_client_field_errors() {
        for (json, expect) in vec![
            // see https://github.com/softprops/hubcaps/issues/31
            (
                r#"{"message": "Validation Failed","errors":
                [{
                    "resource": "Release",
                    "code": "custom",
                    "message": "Published releases must have a valid tag"
                }]}"#,
                ClientError {
                    message: "Validation Failed".to_owned(),
                    errors: Some(vec![FieldErr {
                        resource: "Release".to_owned(),
                        code: "custom".to_owned(),
                        field: None,
                        message: Some(
                            "Published releases \
                             must have a valid tag"
                                .to_owned(),
                        ),
                        documentation_url: None,
                    }]),
                    documentation_url: None,
                },
            ),
        ] {
            assert_eq!(serde_json::from_str::<ClientError>(json).unwrap(), expect);
        }
    }

    #[test]
    fn deserialize_client_top_level_documentation_url() {
        let json = serde_json::json!({
            "message": "Not Found",
            "documentation_url": "https://developer.github.com/v3/activity/watching/#set-a-repository-subscription"
        });
        let expect = ClientError {
            message: String::from("Not Found"),
            errors: None,
            documentation_url: Some(String::from(
                "https://developer.github.com/v3/activity/watching/#set-a-repository-subscription",
            )),
        };
        assert_eq!(serde_json::from_value::<ClientError>(json).unwrap(), expect)
    }
}