1use reqwest::StatusCode;
2use serde_json::Value;
3use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
7
8#[derive(Clone, Debug)]
10pub struct ApiError {
11 pub status: StatusCode,
13 pub code: Option<String>,
15 pub message: String,
17 pub body: Value,
19}
20
21impl fmt::Display for ApiError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 write!(f, "Umami returned {}: {}", self.status, self.message)
24 }
25}
26
27impl std::error::Error for ApiError {}
28
29#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum Error {
33 #[error("invalid Umami endpoint URL: {0}")]
35 InvalidUrl(#[from] url::ParseError),
36
37 #[error("invalid Umami endpoint: {0}")]
39 InvalidEndpoint(String),
40
41 #[error("invalid Umami website ID `{value}`")]
43 InvalidWebsiteId {
44 value: String,
46 #[source]
48 source: uuid::Error,
49 },
50
51 #[error("invalid HTTP user-agent")]
53 InvalidUserAgent(#[from] reqwest::header::InvalidHeaderValue),
54
55 #[error("HTTP user-agent cannot be empty")]
57 EmptyUserAgent,
58
59 #[error("invalid Umami cache header")]
61 InvalidCacheHeader(reqwest::header::InvalidHeaderValue),
62
63 #[error("invalid event properties: {0}")]
65 InvalidProperties(String),
66
67 #[error("invalid event name: {0}")]
69 InvalidEventName(String),
70
71 #[error("invalid performance metric `{name}`: expected {expected}, got {value}")]
73 InvalidMetric {
74 name: &'static str,
76 expected: &'static str,
78 value: f64,
80 },
81
82 #[error("{0}")]
84 InvalidTrack(String),
85
86 #[error("analytics batch has {len} items; Umami accepts at most {max}")]
88 BatchTooLarge {
89 len: usize,
91 max: usize,
93 },
94
95 #[error("an analytics batch can only contain tracks from the same client and session")]
97 MismatchedBatch,
98
99 #[error(transparent)]
101 Http(#[from] reqwest::Error),
102
103 #[error(transparent)]
105 Api(#[from] ApiError),
106
107 #[error("could not decode Umami response with status {status}: {source}")]
109 Decode {
110 status: StatusCode,
112 #[source]
114 source: serde_json::Error,
115 body: String,
117 },
118}
119
120impl Error {
121 #[must_use]
123 pub fn status(&self) -> Option<StatusCode> {
124 match self {
125 Self::Api(error) => Some(error.status),
126 Self::Decode { status, .. } => Some(*status),
127 Self::Http(error) => error.status(),
128 _ => None,
129 }
130 }
131
132 #[must_use]
138 pub fn is_retryable(&self) -> bool {
139 match self {
140 Self::Http(error) => error.is_timeout() || error.is_connect(),
141 Self::Api(error) => {
142 error.status == StatusCode::TOO_MANY_REQUESTS || error.status.is_server_error()
143 }
144 _ => false,
145 }
146 }
147}