Skip to main content

rust_umami/
error.rs

1use reqwest::StatusCode;
2use serde_json::Value;
3use std::fmt;
4
5/// Result type used throughout the crate.
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// An error returned by Umami for a non-successful HTTP response.
9#[derive(Clone, Debug)]
10pub struct ApiError {
11    /// HTTP status returned by Umami.
12    pub status: StatusCode,
13    /// Stable Umami error code, when provided.
14    pub code: Option<String>,
15    /// Human-readable error message.
16    pub message: String,
17    /// Complete JSON response body.
18    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/// Errors produced while configuring the client or sending analytics.
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum Error {
33    /// An endpoint URL could not be parsed.
34    #[error("invalid Umami endpoint URL: {0}")]
35    InvalidUrl(#[from] url::ParseError),
36
37    /// The endpoint URL is not an HTTP(S) URL or cannot be used as a base URL.
38    #[error("invalid Umami endpoint: {0}")]
39    InvalidEndpoint(String),
40
41    /// The website ID is not a UUID accepted by Umami.
42    #[error("invalid Umami website ID `{value}`")]
43    InvalidWebsiteId {
44        /// The rejected value.
45        value: String,
46        /// UUID parsing error.
47        #[source]
48        source: uuid::Error,
49    },
50
51    /// The configured HTTP user-agent is not a valid header value.
52    #[error("invalid HTTP user-agent")]
53    InvalidUserAgent(#[from] reqwest::header::InvalidHeaderValue),
54
55    /// Umami requires a non-empty HTTP user-agent.
56    #[error("HTTP user-agent cannot be empty")]
57    EmptyUserAgent,
58
59    /// A cache value returned by Umami could not be represented as a header.
60    #[error("invalid Umami cache header")]
61    InvalidCacheHeader(reqwest::header::InvalidHeaderValue),
62
63    /// Event properties could not be represented as a JSON object.
64    #[error("invalid event properties: {0}")]
65    InvalidProperties(String),
66
67    /// A custom event name is invalid.
68    #[error("invalid event name: {0}")]
69    InvalidEventName(String),
70
71    /// A performance metric is outside Umami's accepted range.
72    #[error("invalid performance metric `{name}`: expected {expected}, got {value}")]
73    InvalidMetric {
74        /// Metric name.
75        name: &'static str,
76        /// Accepted range.
77        expected: &'static str,
78        /// Rejected value.
79        value: f64,
80    },
81
82    /// A track contains fields that do not apply to its kind.
83    #[error("{0}")]
84    InvalidTrack(String),
85
86    /// Umami accepts at most 500 items in one batch.
87    #[error("analytics batch has {len} items; Umami accepts at most {max}")]
88    BatchTooLarge {
89        /// Submitted item count.
90        len: usize,
91        /// Umami's maximum item count.
92        max: usize,
93    },
94
95    /// A batch received an event created by another client or session.
96    #[error("an analytics batch can only contain tracks from the same client and session")]
97    MismatchedBatch,
98
99    /// The HTTP client failed to build or send a request.
100    #[error(transparent)]
101    Http(#[from] reqwest::Error),
102
103    /// Umami returned a non-successful HTTP status.
104    #[error(transparent)]
105    Api(#[from] ApiError),
106
107    /// A successful response was not valid JSON for the expected response type.
108    #[error("could not decode Umami response with status {status}: {source}")]
109    Decode {
110        /// HTTP status returned by Umami.
111        status: StatusCode,
112        /// JSON decoding error.
113        #[source]
114        source: serde_json::Error,
115        /// A bounded, lossy response-body excerpt useful for diagnostics.
116        body: String,
117    },
118}
119
120impl Error {
121    /// Returns the HTTP status when this error came from an Umami response.
122    #[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    /// Returns whether this error is retryable under a conservative policy.
133    ///
134    /// Timeouts, connection failures, HTTP 429, and server errors are
135    /// considered retryable. The crate does not retry automatically because a
136    /// retry can duplicate an analytics event.
137    #[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}