pub enum CacheError {
Expired {
key: String,
},
Miss {
key: String,
},
Full {
key: String,
},
OperationFailed {
reason: String,
},
}Expand description
Cache-related errors for token and data caching operations.
This enum provides detailed error classification for caching operations throughout the application, particularly for authentication token caching and other temporary data storage. Each error variant includes relevant context to aid in cache management and error recovery.
§Error Categories
§Cache Entry Lifecycle Errors
§Cache Capacity and Management Errors
Full- Cache has reached capacity limitsOperationFailed- General cache operation failures
§Examples
§Token Cache Error Handling
use quetty_server::common::errors::CacheError;
async fn handle_token_cache_error(error: CacheError, token_key: &str) {
match error {
CacheError::Expired { key } => {
println!("Token expired for key: {}", key);
// Trigger token refresh
refresh_token(&key).await;
}
CacheError::Miss { key } => {
println!("Token not found in cache: {}", key);
// Authenticate and cache new token
authenticate_and_cache(&key).await;
}
CacheError::Full { key } => {
println!("Cache full, cannot store token for: {}", key);
// Implement cache eviction strategy
evict_oldest_entries().await;
retry_cache_operation(&key).await;
}
CacheError::OperationFailed { reason } => {
eprintln!("Cache operation failed: {}", reason);
// Log error and use alternative storage
fallback_to_memory_cache(&token_key).await;
}
}
}§Cache Management Patterns
use quetty_server::common::errors::CacheError;
async fn get_or_create_cached_item<T>(
cache_key: &str,
create_fn: impl Fn() -> Result<T, String>
) -> Result<T, CacheError> {
// Try to get from cache first
match get_from_cache(cache_key).await {
Ok(item) => Ok(item),
Err(CacheError::Miss { .. }) => {
// Cache miss - create and cache the item
match create_fn() {
Ok(item) => {
// Attempt to cache the new item
if let Err(cache_err) = cache_item(cache_key, &item).await {
// Log cache failure but return the item anyway
log::warn!("Failed to cache item: {}", cache_err);
}
Ok(item)
}
Err(create_error) => {
Err(CacheError::OperationFailed {
reason: format!("Item creation failed: {}", create_error)
})
}
}
}
Err(CacheError::Expired { key }) => {
// Cache expired - remove and recreate
remove_from_cache(&key).await;
create_fn().map_err(|e| CacheError::OperationFailed {
reason: format!("Recreation after expiry failed: {}", e)
})
}
Err(other) => Err(other),
}
}§Cache Health Monitoring
use quetty_server::common::errors::CacheError;
struct CacheMetrics {
hits: u64,
misses: u64,
expirations: u64,
failures: u64,
}
fn update_cache_metrics(error: &CacheError, metrics: &mut CacheMetrics) {
match error {
CacheError::Miss { .. } => {
metrics.misses += 1;
log::debug!("Cache miss recorded");
}
CacheError::Expired { .. } => {
metrics.expirations += 1;
log::debug!("Cache expiration recorded");
}
CacheError::Full { .. } | CacheError::OperationFailed { .. } => {
metrics.failures += 1;
log::warn!("Cache failure recorded: {}", error);
}
}
}
fn calculate_cache_hit_rate(metrics: &CacheMetrics) -> f64 {
let total_requests = metrics.hits + metrics.misses;
if total_requests == 0 {
0.0
} else {
metrics.hits as f64 / total_requests as f64
}
}§Integration with Authentication
use quetty_server::common::errors::CacheError;
use quetty_server::auth::TokenRefreshError;
async fn get_valid_token(user_id: &str) -> Result<String, TokenRefreshError> {
match get_cached_token(user_id).await {
Ok(token) => Ok(token),
Err(CacheError::Miss { .. }) | Err(CacheError::Expired { .. }) => {
// Cache miss or expiry - refresh token
let new_token = refresh_user_token(user_id).await?;
// Attempt to cache the new token
if let Err(cache_err) = cache_token(user_id, &new_token).await {
log::warn!("Failed to cache refreshed token: {}", cache_err);
// Continue anyway - token is still valid
}
Ok(new_token)
}
Err(CacheError::OperationFailed { reason }) => {
// Cache operation failed - try refresh anyway
log::error!("Cache operation failed: {}", reason);
refresh_user_token(user_id).await
}
Err(CacheError::Full { .. }) => {
// Cache full - evict and retry
evict_expired_tokens().await;
match get_cached_token(user_id).await {
Ok(token) => Ok(token),
Err(_) => refresh_user_token(user_id).await,
}
}
}
}§Cache Strategies
§Error-Based Cache Management
- Miss: Create and cache new data
- Expired: Remove expired entry and recreate
- Full: Implement LRU or TTL-based eviction
- Operation Failed: Fall back to direct data access
§Performance Considerations
- Cache errors should not block critical operations
- Implement graceful degradation when cache is unavailable
- Monitor cache hit rates and error frequencies
- Use appropriate TTL values to balance freshness and performance
Variants§
Expired
Cache entry has expired and is no longer valid.
This error occurs when attempting to access a cache entry that has exceeded its time-to-live (TTL). The entry should be removed and recreated if needed.
§Fields
key: The cache key for the expired entry
§Recovery
- Remove the expired entry from cache
- Recreate the data if needed
- Update cache with fresh data and appropriate TTL
Miss
Requested cache entry was not found.
This error occurs when attempting to retrieve a cache entry that doesn’t exist. This is a normal condition for cold cache scenarios or when entries have been evicted.
§Fields
key: The cache key that was not found
§Recovery
- Create the data using the original source
- Cache the newly created data for future requests
- Consider pre-warming cache for frequently accessed items
Full
Cache has reached its capacity limit.
This error occurs when attempting to add a new entry to a cache that has reached its maximum capacity. This requires cache management strategies like eviction.
§Fields
key: The cache key that couldn’t be added
§Recovery
- Implement cache eviction strategy (LRU, TTL-based, etc.)
- Remove expired or least recently used entries
- Consider increasing cache capacity if appropriate
- Retry the cache operation after eviction
OperationFailed
General cache operation failure.
This error represents various cache operation failures that don’t fit other categories, such as I/O errors, serialization failures, or cache system unavailability.
§Fields
reason: Detailed description of the operation failure
§Recovery
- Log the detailed error for debugging
- Fall back to direct data access without caching
- Consider cache system health checks
- Implement retry logic for transient failures
Trait Implementations§
Source§impl Debug for CacheError
impl Debug for CacheError
Source§impl Display for CacheError
impl Display for CacheError
Source§impl Error for CacheError
impl Error for CacheError
1.30.0 · Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
Source§impl From<CacheError> for ServiceBusError
impl From<CacheError> for ServiceBusError
Source§fn from(err: CacheError) -> Self
fn from(err: CacheError) -> Self
Auto Trait Implementations§
impl Freeze for CacheError
impl RefUnwindSafe for CacheError
impl Send for CacheError
impl Sync for CacheError
impl Unpin for CacheError
impl UnwindSafe for CacheError
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<T> ToStringFallible for Twhere
T: Display,
impl<T> ToStringFallible for Twhere
T: Display,
Source§fn try_to_string(&self) -> Result<String, TryReserveError>
fn try_to_string(&self) -> Result<String, TryReserveError>
ToString::to_string, but without panic on OOM.