use std::fmt;
use std::time::Duration;
use reqwest::header::HeaderMap;
use crate::ratelimit::RateLimit;
use crate::types::{LimitPolicy, ProblemCode};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Api(Box<ApiError>),
#[error("no answer from the API ({operation}): {source}")]
Transport {
operation: &'static str,
#[source]
source: reqwest::Error,
},
#[error("an answer is not as the API documents it ({operation}): {message}")]
Decode {
operation: &'static str,
message: String,
},
#[error("{0}")]
Config(String),
}
impl Error {
pub fn api(&self) -> Option<&ApiError> {
match self {
Error::Api(error) => Some(error),
_ => None,
}
}
}
impl From<ApiError> for Error {
fn from(error: ApiError) -> Self {
Error::Api(Box::new(error))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ApiErrorKind {
BadRequest,
Authentication,
NotFound,
RateLimited,
Server,
Other,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ApiError {
pub status: u16,
pub code: ProblemCode,
pub code_text: String,
pub title: String,
pub detail: String,
pub type_url: String,
pub request_id: String,
pub retry_after: Option<Duration>,
pub violated_policies: Vec<LimitPolicy>,
pub rate_limit: Option<RateLimit>,
pub headers: HeaderMap,
}
impl ApiError {
pub fn kind(&self) -> ApiErrorKind {
match self.status {
400 => ApiErrorKind::BadRequest,
401 => ApiErrorKind::Authentication,
404 => ApiErrorKind::NotFound,
429 => ApiErrorKind::RateLimited,
500.. => ApiErrorKind::Server,
_ => ApiErrorKind::Other,
}
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} ({}): {} [{}]",
self.code_text, self.status, self.detail, self.request_id
)
}
}
impl std::error::Error for ApiError {}