use std::time::Duration;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct HttpError {
source: reqwest::Error,
}
impl HttpError {
pub(crate) fn new(source: reqwest::Error) -> Self {
Self { source }
}
}
impl std::fmt::Display for HttpError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.fmt(formatter)
}
}
impl std::error::Error for HttpError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("HTTP request failed: {0}")]
Http(#[source] HttpError),
#[error("request timed out after {0:?}")]
Timeout(Duration),
#[error("Open-Meteo API error ({status}): {reason}")]
Api {
status: u16,
reason: String,
},
#[error("rate limited (HTTP 429); retry-after: {retry_after:?}")]
RateLimited {
retry_after: Option<Duration>,
},
#[error("failed to decode JSON response: {0}")]
JsonDecode(#[from] serde_json::Error),
#[error("invalid API response: {reason}")]
InvalidResponse {
reason: String,
},
#[error("invalid parameter `{field}`: {reason}")]
InvalidParam {
field: &'static str,
reason: String,
},
#[error("mutually exclusive parameters: {first} and {second} cannot both be set")]
MutuallyExclusive {
first: &'static str,
second: &'static str,
},
#[error("failed to parse timestamp `{value}`: {reason}")]
TimeParse {
value: String,
reason: String,
},
}
impl From<reqwest::Error> for Error {
fn from(source: reqwest::Error) -> Self {
Self::Http(HttpError::new(source))
}
}
pub(crate) fn map_reqwest_error(source: reqwest::Error, timeout: Duration) -> Error {
if source.is_timeout() {
Error::Timeout(timeout)
} else {
Error::Http(HttpError::new(source))
}
}