Skip to main content

thinkingdata_core/
error.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Error type shared by the whole SDK.
16
17use std::fmt;
18
19/// The result type used across the SDK.
20pub type Result<T> = std::result::Result<T, TDError>;
21
22/// Errors returned by the ThinkingData SDK.
23///
24/// External error sources (HTTP, IO, JSON, URL) are preserved as formatted
25/// messages so the error itself stays [`Clone`], which the consumers need to
26/// publish results — such as the outcome of `close` — to concurrent callers.
27#[derive(Debug, Clone, thiserror::Error)]
28pub enum TDError {
29    /// A generic error message, mirroring the error strings of the official SDKs.
30    #[error("{0}")]
31    Message(String),
32
33    /// An HTTP transport or response error.
34    #[error("http request failed: {0}")]
35    Http(String),
36
37    /// A file system error.
38    #[error("io operation failed: {0}")]
39    Io(String),
40
41    /// A JSON serialization error.
42    #[error("json serialization failed: {0}")]
43    Json(String),
44
45    /// The configured server URL is invalid.
46    #[error("invalid server url: {0}")]
47    InvalidServerUrl(String),
48
49    /// `event_name` is required for every `track*` data type.
50    #[error("the event name must be provided")]
51    EmptyEventName,
52
53    /// `event_id` is required for `track_update` and `track_overwrite`.
54    #[error("the event id must be provided")]
55    EmptyEventId,
56
57    /// `first_check_id` is required for first events.
58    #[error("the 'firstCheckId' must be provided")]
59    EmptyFirstCheckId,
60
61    /// The event name does not match `^[a-zA-Z#][A-Za-z0-9_]{0,49}$`.
62    #[error("invalid event name: {0}")]
63    InvalidEventName(String),
64
65    /// A property key does not match `^[a-zA-Z#][A-Za-z0-9_]{0,49}$`.
66    /// Only reported by stringent consumers (debug consumer).
67    #[error("invalid property key: {0}")]
68    InvalidPropertyKey(String),
69
70    /// A `user_add` property value is not a number.
71    #[error("invalid property value: only numbers is supported by UserAdd")]
72    InvalidUserAddValue,
73
74    /// Both `account_id` and `distinct_id` were empty.
75    #[error("invalid parameters: account_id and distinct_id cannot be empty at the same time")]
76    EmptyIds,
77
78    /// `user_unset` was called without any keys.
79    #[error("invalid params for UserUnset: keys is nil")]
80    EmptyUnsetKeys,
81
82    /// The batch consumer has been closed and no longer accepts data.
83    #[error("batch consumer has been closed")]
84    ConsumerClosed,
85}
86
87impl From<reqwest::Error> for TDError {
88    fn from(err: reqwest::Error) -> Self {
89        TDError::Http(err.to_string())
90    }
91}
92
93impl From<std::io::Error> for TDError {
94    fn from(err: std::io::Error) -> Self {
95        TDError::Io(err.to_string())
96    }
97}
98
99impl From<serde_json::Error> for TDError {
100    fn from(err: serde_json::Error) -> Self {
101        TDError::Json(err.to_string())
102    }
103}
104
105impl From<url::ParseError> for TDError {
106    fn from(err: url::ParseError) -> Self {
107        TDError::InvalidServerUrl(err.to_string())
108    }
109}
110
111impl TDError {
112    /// Shorthand for [`TDError::Message`] with a formatted string.
113    pub fn msg(message: impl fmt::Display) -> Self {
114        TDError::Message(message.to_string())
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn clone_preserves_message() {
124        let err = TDError::InvalidEventName("bad name".to_string());
125        let cloned = err.clone();
126        assert_eq!(cloned.to_string(), "invalid event name: bad name");
127    }
128
129    #[test]
130    fn from_io_error_wraps_message() {
131        let err: TDError = std::io::Error::new(std::io::ErrorKind::NotFound, "missing").into();
132        assert!(err.to_string().contains("missing"));
133    }
134}