Add MigrateToChatId and RetryAfter to RequestError

This commit is contained in:
Waffle 2019-09-19 01:59:16 +03:00
parent 9cc5806f07
commit fe75e0ff07
2 changed files with 44 additions and 24 deletions

View file

@ -57,18 +57,7 @@ pub async fn request_multipart<T: DeserializeOwned>(
)
.map_err(RequestError::InvalidJson)?;
match response {
TelegramResponse::Ok { result, .. } => Ok(result),
TelegramResponse::Err {
description,
error_code,
response_parameters: _,
..
} => Err(RequestError::ApiError {
description,
status_code: StatusCode::from_u16(error_code).unwrap(),
}),
}
response.into()
}
pub async fn request_json<T: DeserializeOwned, P: Serialize>(
@ -89,18 +78,7 @@ pub async fn request_json<T: DeserializeOwned, P: Serialize>(
)
.map_err(RequestError::InvalidJson)?;
match response {
TelegramResponse::Ok { result, .. } => Ok(result),
TelegramResponse::Err {
description,
error_code,
response_parameters: _,
..
} => Err(RequestError::ApiError {
description,
status_code: StatusCode::from_u16(error_code).unwrap(),
}),
}
response.into()
}
#[derive(Deserialize)]
@ -124,6 +102,36 @@ enum TelegramResponse<R> {
},
}
impl<R> Into<ResponseResult<R>> for TelegramResponse<R> {
fn into(self) -> Result<R, RequestError> {
match self {
TelegramResponse::Ok { result, .. } => Ok(result),
TelegramResponse::Err {
description,
error_code,
response_parameters,
..
} => {
if let Some(params) = response_parameters {
match params {
ResponseParameters::RetryAfter(i) => {
Err(RequestError::RetryAfter(i))
}
ResponseParameters::MigrateToChatId(to) => {
Err(RequestError::MigrateToChatId(to))
}
}
} else {
Err(RequestError::ApiError {
description,
status_code: StatusCode::from_u16(error_code).unwrap(),
})
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -16,6 +16,16 @@ pub enum RequestError {
description: String,
},
/// The group has been migrated to a supergroup with the specified
/// identifier.
#[display(fmt = "The group has been migrated to a supergroup with id {id}", id = _0)]
MigrateToChatId(i64),
/// In case of exceeding flood control, the number of seconds left to wait
/// before the request can be repeated
#[display(fmt = "Retry after {secs} seconds", secs = _0)]
RetryAfter(i32),
#[display(fmt = "Network error: {err}", err = _0)]
NetworkError(reqwest::Error),
@ -27,6 +37,8 @@ impl std::error::Error for RequestError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
RequestError::ApiError { .. } => None,
RequestError::MigrateToChatId(_) => None,
RequestError::RetryAfter(_) => None,
RequestError::NetworkError(err) => Some(err),
RequestError::InvalidJson(err) => Some(err),
}