Skip to main content

threatflux_cache/
error.rs

1//! Error types for the cache library
2
3use std::io;
4use thiserror::Error;
5
6/// Main error type for cache operations
7#[derive(Error, Debug)]
8#[non_exhaustive]
9pub enum CacheError {
10    /// I/O error occurred during cache operations
11    #[error("I/O error: {0}")]
12    Io(#[from] io::Error),
13
14    /// Serialization error
15    #[error("Serialization error: {0}")]
16    Serialization(String),
17
18    /// Deserialization error
19    #[error("Deserialization error: {0}")]
20    Deserialization(String),
21
22    /// Cache capacity exceeded
23    #[error("Cache capacity exceeded: {message}")]
24    CapacityExceeded {
25        /// Error message
26        message: String,
27    },
28
29    /// Storage backend error
30    #[error("Storage backend error: {0}")]
31    StorageBackend(String),
32
33    /// Entry not found
34    #[error("Entry not found for key")]
35    NotFound,
36
37    /// Invalid configuration
38    #[error("Invalid configuration: {0}")]
39    InvalidConfiguration(String),
40
41    /// A persistence snapshot exceeded the configured byte limit
42    #[error("Persistence snapshot is too large ({actual_bytes} bytes; limit is {max_bytes})")]
43    SnapshotTooLarge {
44        /// Actual snapshot size in bytes
45        actual_bytes: u64,
46        /// Configured maximum size in bytes
47        max_bytes: u64,
48    },
49
50    /// The persisted data uses an unsupported layout or format version
51    #[error("Unsupported persistence format: {0}")]
52    UnsupportedPersistenceFormat(String),
53
54    /// Custom error for extensions
55    #[error("Custom error: {0}")]
56    Custom(String),
57}
58
59/// Result type alias for cache operations
60pub type Result<T> = std::result::Result<T, CacheError>;
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_cache_error_variants() {
68        let io_err: CacheError = io::Error::other("oops").into();
69        assert!(matches!(io_err, CacheError::Io(_)));
70
71        let ser_err = CacheError::Serialization("ser".into());
72        assert_eq!(format!("{ser_err}"), "Serialization error: ser");
73
74        let des_err = CacheError::Deserialization("de".into());
75        assert_eq!(format!("{des_err}"), "Deserialization error: de");
76
77        let cap_err = CacheError::CapacityExceeded {
78            message: "full".into(),
79        };
80        assert!(matches!(cap_err, CacheError::CapacityExceeded { .. }));
81
82        let backend_err = CacheError::StorageBackend("be".into());
83        assert!(matches!(backend_err, CacheError::StorageBackend(_)));
84
85        let not_found = CacheError::NotFound;
86        assert_eq!(format!("{not_found}"), "Entry not found for key");
87
88        let custom = CacheError::Custom("c".into());
89        assert_eq!(format!("{custom}"), "Custom error: c");
90    }
91}