Skip to main content

multi_tier_cache/
error.rs

1use std::fmt;
2use thiserror::Error;
3
4#[cfg(feature = "redis")]
5use redis::RedisError;
6
7/// Result type for cache operations
8pub type CacheResult<T> = std::result::Result<T, CacheError>;
9
10/// Strongly-typed error enum for multi-tier-cache
11#[derive(Error, Debug, Clone)]
12pub enum CacheError {
13    /// Error from a cache backend (Redis, Memcached, etc.)
14    BackendError(String),
15    /// Error during serialization/deserialization
16    SerializationError(String),
17    /// Error during cross-instance invalidation
18    InvalidationError(String),
19    /// Configuration or initialization error
20    ConfigError(String),
21    /// Key not found in cache
22    NotFound,
23    /// Internal logic error or unexpected state
24    InternalError(String),
25}
26
27impl fmt::Display for CacheError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Self::BackendError(msg) => write!(f, "Backend error: {msg}"),
31            Self::SerializationError(msg) => write!(f, "Serialization error: {msg}"),
32            Self::InvalidationError(msg) => write!(f, "Invalidation error: {msg}"),
33            Self::ConfigError(msg) => write!(f, "Configuration error: {msg}"),
34            Self::NotFound => write!(f, "Key not found"),
35            Self::InternalError(msg) => write!(f, "Internal error: {msg}"),
36        }
37    }
38}
39
40#[cfg(feature = "redis")]
41impl From<RedisError> for CacheError {
42    fn from(err: RedisError) -> Self {
43        Self::BackendError(err.to_string())
44    }
45}
46
47impl From<serde_json::Error> for CacheError {
48    fn from(err: serde_json::Error) -> Self {
49        Self::SerializationError(err.to_string())
50    }
51}
52
53#[cfg(feature = "msgpack")]
54impl From<rmp_serde::decode::Error> for CacheError {
55    fn from(err: rmp_serde::decode::Error) -> Self {
56        Self::SerializationError(err.to_string())
57    }
58}
59
60impl From<std::num::TryFromIntError> for CacheError {
61    fn from(err: std::num::TryFromIntError) -> Self {
62        Self::ConfigError(err.to_string())
63    }
64}
65
66#[cfg(feature = "backend-memcached")]
67impl From<memcache::MemcacheError> for CacheError {
68    fn from(err: memcache::MemcacheError) -> Self {
69        Self::BackendError(err.to_string())
70    }
71}