use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone)]
pub enum Error {
SerializationError(String),
DeserializationError(String),
ValidationError(String),
CacheMiss,
BackendError(String),
RepositoryError(String),
Timeout(String),
ConfigError(String),
NotImplemented(String),
InvalidCacheEntry(String),
VersionMismatch {
expected: u32,
found: u32,
},
Other(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
Error::DeserializationError(msg) => write!(f, "Deserialization error: {}", msg),
Error::ValidationError(msg) => write!(f, "Validation error: {}", msg),
Error::CacheMiss => write!(f, "Cache miss"),
Error::BackendError(msg) => write!(f, "Backend error: {}", msg),
Error::RepositoryError(msg) => write!(f, "Repository error: {}", msg),
Error::Timeout(msg) => write!(f, "Timeout: {}", msg),
Error::ConfigError(msg) => write!(f, "Config error: {}", msg),
Error::NotImplemented(msg) => write!(f, "Not implemented: {}", msg),
Error::InvalidCacheEntry(msg) => {
write!(f, "Invalid cache entry: {}", msg)
}
Error::VersionMismatch { expected, found } => {
write!(
f,
"Cache version mismatch: expected {}, found {}",
expected, found
)
}
Error::Other(msg) => write!(f, "Error: {}", msg),
}
}
}
impl std::error::Error for Error {}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
if e.is_io() {
Error::BackendError(e.to_string())
} else if e.is_syntax() {
Error::DeserializationError(e.to_string())
} else {
Error::SerializationError(e.to_string())
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::BackendError(e.to_string())
}
}
impl From<String> for Error {
fn from(e: String) -> Self {
Error::Other(e)
}
}
impl From<&str> for Error {
fn from(e: &str) -> Self {
Error::Other(e.to_string())
}
}
#[cfg(feature = "redis")]
impl From<redis::RedisError> for Error {
fn from(e: redis::RedisError) -> Self {
Error::BackendError(format!("Redis error: {}", e))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_display() {
let err = Error::ValidationError("Test".to_string());
assert_eq!(err.to_string(), "Validation error: Test");
}
#[test]
fn test_error_from_string() {
let err: Error = "test error".into();
assert!(matches!(err, Error::Other(_)));
}
}