CacheError

Enum CacheError 

Source
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

  • Expired - Cache entry has exceeded its time-to-live
  • Miss - Requested cache entry doesn’t exist

§Cache Capacity and Management Errors

§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

Fields

§

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

Fields

§

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

Fields

§

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

Fields

§reason: String

Trait Implementations§

Source§

impl Debug for CacheError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for CacheError

Source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for CacheError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<CacheError> for ServiceBusError

Source§

fn from(err: CacheError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> SendBound for T
where T: Send,