use std::fmt;
pub type Result<T> = std::result::Result<T, TDError>;
#[derive(Debug, Clone, thiserror::Error)]
pub enum TDError {
#[error("{0}")]
Message(String),
#[error("http request failed: {0}")]
Http(String),
#[error("io operation failed: {0}")]
Io(String),
#[error("json serialization failed: {0}")]
Json(String),
#[error("invalid server url: {0}")]
InvalidServerUrl(String),
#[error("the event name must be provided")]
EmptyEventName,
#[error("the event id must be provided")]
EmptyEventId,
#[error("the 'firstCheckId' must be provided")]
EmptyFirstCheckId,
#[error("invalid event name: {0}")]
InvalidEventName(String),
#[error("invalid property key: {0}")]
InvalidPropertyKey(String),
#[error("invalid property value: only numbers is supported by UserAdd")]
InvalidUserAddValue,
#[error("invalid parameters: account_id and distinct_id cannot be empty at the same time")]
EmptyIds,
#[error("invalid params for UserUnset: keys is nil")]
EmptyUnsetKeys,
#[error("batch consumer has been closed")]
ConsumerClosed,
}
impl From<reqwest::Error> for TDError {
fn from(err: reqwest::Error) -> Self {
TDError::Http(err.to_string())
}
}
impl From<std::io::Error> for TDError {
fn from(err: std::io::Error) -> Self {
TDError::Io(err.to_string())
}
}
impl From<serde_json::Error> for TDError {
fn from(err: serde_json::Error) -> Self {
TDError::Json(err.to_string())
}
}
impl From<url::ParseError> for TDError {
fn from(err: url::ParseError) -> Self {
TDError::InvalidServerUrl(err.to_string())
}
}
impl TDError {
pub fn msg(message: impl fmt::Display) -> Self {
TDError::Message(message.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clone_preserves_message() {
let err = TDError::InvalidEventName("bad name".to_string());
let cloned = err.clone();
assert_eq!(cloned.to_string(), "invalid event name: bad name");
}
#[test]
fn from_io_error_wraps_message() {
let err: TDError = std::io::Error::new(std::io::ErrorKind::NotFound, "missing").into();
assert!(err.to_string().contains("missing"));
}
}