use std::fmt;
use std::time::Duration;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{status} {name}: {message}")]
#[non_exhaustive]
Api {
status: u16,
name: String,
message: String,
retry_after: Option<Duration>,
},
#[error("{0}")]
Signature(String),
#[error("{0}")]
Config(String),
#[error("JSON: {0}")]
Json(#[from] serde_json::Error),
}
impl Error {
pub fn status(&self) -> Option<u16> {
match self {
Error::Api { status, .. } => Some(*status),
_ => None,
}
}
pub fn name(&self) -> Option<&str> {
match self {
Error::Api { name, .. } => Some(name),
_ => None,
}
}
pub fn retryable(&self) -> bool {
match self {
Error::Api { status, name, .. } => match status {
0 => true,
409 => name == "concurrent_idempotent_requests",
429 => name != "daily_quota_exceeded",
s => *s >= 500,
},
_ => false,
}
}
pub fn retry_after(&self) -> Option<Duration> {
match self {
Error::Api { retry_after, .. } => *retry_after,
_ => None,
}
}
pub fn is_quota_exceeded(&self) -> bool {
matches!(self, Error::Api { status: 429, name, .. } if name == "daily_quota_exceeded")
}
pub(crate) fn unreachable(err: impl fmt::Display) -> Self {
Error::Api {
status: 0,
name: "application_error".into(),
message: format!("Unable to reach the API: {err}"),
retry_after: None,
}
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;