use crate::http::constants::{FIRST_SERVER_ERROR, TOO_MANY_REQUESTS};
#[derive(Debug, Clone, thiserror::Error)]
pub enum ApiError {
#[error("request failed: {0}")]
Transport(String),
#[error("HTTP {status} {code}: {message}")]
Status {
status: u16,
code: String,
message: String,
},
#[error("unexpected response: {0}")]
Protocol(String),
#[error("{0}")]
Auth(String),
}
impl ApiError {
pub fn is_retryable(&self) -> bool {
match self {
Self::Transport(_) => true,
Self::Status { status, .. } => {
*status == TOO_MANY_REQUESTS || *status >= FIRST_SERVER_ERROR
}
Self::Protocol(_) | Self::Auth(_) => false,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Status { status, .. } => Some(*status),
_ => None,
}
}
pub fn code(&self) -> Option<&str> {
match self {
Self::Status { code, .. } => Some(code.as_str()),
_ => None,
}
}
}
impl From<reqwest::Error> for ApiError {
fn from(error: reqwest::Error) -> Self {
Self::Transport(error.without_url().to_string())
}
}