use reqwest::StatusCode;
use serde_json::Value;
use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Debug)]
pub struct ApiError {
pub status: StatusCode,
pub code: Option<String>,
pub message: String,
pub body: Value,
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Umami returned {}: {}", self.status, self.message)
}
}
impl std::error::Error for ApiError {}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("invalid Umami endpoint URL: {0}")]
InvalidUrl(#[from] url::ParseError),
#[error("invalid Umami endpoint: {0}")]
InvalidEndpoint(String),
#[error("invalid Umami website ID `{value}`")]
InvalidWebsiteId {
value: String,
#[source]
source: uuid::Error,
},
#[error("invalid HTTP user-agent")]
InvalidUserAgent(#[from] reqwest::header::InvalidHeaderValue),
#[error("HTTP user-agent cannot be empty")]
EmptyUserAgent,
#[error("invalid Umami cache header")]
InvalidCacheHeader(reqwest::header::InvalidHeaderValue),
#[error("invalid event properties: {0}")]
InvalidProperties(String),
#[error("invalid event name: {0}")]
InvalidEventName(String),
#[error("invalid performance metric `{name}`: expected {expected}, got {value}")]
InvalidMetric {
name: &'static str,
expected: &'static str,
value: f64,
},
#[error("{0}")]
InvalidTrack(String),
#[error("analytics batch has {len} items; Umami accepts at most {max}")]
BatchTooLarge {
len: usize,
max: usize,
},
#[error("an analytics batch can only contain tracks from the same client and session")]
MismatchedBatch,
#[error(transparent)]
Http(#[from] reqwest::Error),
#[error(transparent)]
Api(#[from] ApiError),
#[error("could not decode Umami response with status {status}: {source}")]
Decode {
status: StatusCode,
#[source]
source: serde_json::Error,
body: String,
},
}
impl Error {
#[must_use]
pub fn status(&self) -> Option<StatusCode> {
match self {
Self::Api(error) => Some(error.status),
Self::Decode { status, .. } => Some(*status),
Self::Http(error) => error.status(),
_ => None,
}
}
#[must_use]
pub fn is_retryable(&self) -> bool {
match self {
Self::Http(error) => error.is_timeout() || error.is_connect(),
Self::Api(error) => {
error.status == StatusCode::TOO_MANY_REQUESTS || error.status.is_server_error()
}
_ => false,
}
}
}