Skip to main content

sisa_caching_redis/
error.rs

1//! The Redis store's errors.
2
3use serde_json::error::Category;
4use sisa_caching_core::cache::CacheError;
5
6/// What went wrong with the JSON, without quoting it.
7fn json_message(error: &serde_json::Error) -> String {
8    let (line, column) = (error.line(), error.column());
9
10    // An encoding error has no position, and neither has a decoding error that the type raises
11    // itself, such as an untagged enum that no variant fits.
12    if line == 0 {
13        return "the value couldn't be encoded as JSON, or the stored JSON doesn't fit the requested type"
14            .to_owned();
15    }
16
17    match error.classify() {
18        Category::Data => {
19            format!("the stored JSON doesn't fit the requested type at line {line} column {column}")
20        }
21        _ => format!("the stored data isn't valid JSON at line {line} column {column}"),
22    }
23}
24
25/// Errors from Redis-backed cache operations: the shared [`CacheError`]s, plus Redis and JSON
26/// failures.
27#[derive(Debug, thiserror::Error)]
28#[non_exhaustive]
29pub enum RedisCacheError {
30    /// Shared cache errors, such as a `CacheOptions` TTL over 365 days.
31    #[error(transparent)]
32    Cache(#[from] CacheError),
33
34    /// Connection, command or protocol errors from Redis.
35    #[error(transparent)]
36    Redis(#[from] redis::RedisError),
37
38    /// A value couldn't be encoded to, or decoded from, JSON. Decoding fails when the stored JSON
39    /// no longer fits the type, such as after a field was added without `#[serde(default)]`. The
40    /// message says where when serde knows, but leaves serde's own message, which can quote the
41    /// data, to the error's [`source`](std::error::Error::source).
42    #[error("{}", json_message(.0))]
43    Json(#[from] serde_json::Error),
44}
45
46/// A `Result` whose error is a [`RedisCacheError`].
47pub type Result<T> = std::result::Result<T, RedisCacheError>;
48
49#[cfg(test)]
50mod tests {
51    use std::error::Error;
52
53    use super::*;
54
55    #[test]
56    fn a_json_error_says_where_it_can_without_quoting_the_data() {
57        // An untagged enum raises its own error when no variant fits, and serde gives that no
58        // position.
59        #[derive(Debug, serde::Deserialize)]
60        #[serde(untagged)]
61        enum Null {
62            Null,
63        }
64
65        let decoded = serde_json::from_str::<u64>(r#""ada@example.com""#).unwrap_err();
66        let error = RedisCacheError::from(decoded);
67        let source = error.source().unwrap().to_string();
68
69        assert_eq!(
70            error.to_string(),
71            "the stored JSON doesn't fit the requested type at line 1 column 17"
72        );
73        assert!(source.contains("ada@example.com"), "{source}");
74
75        let unplaced = serde_json::from_str::<Null>(r#""ada@example.com""#).unwrap_err();
76
77        assert_eq!(
78            RedisCacheError::from(unplaced).to_string(),
79            "the value couldn't be encoded as JSON, or the stored JSON doesn't fit the requested type"
80        );
81    }
82}