sisa_caching_redis/
error.rs1use serde_json::error::Category;
4use sisa_caching_core::cache::CacheError;
5
6fn json_message(error: &serde_json::Error) -> String {
8 let (line, column) = (error.line(), error.column());
9
10 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#[derive(Debug, thiserror::Error)]
28#[non_exhaustive]
29pub enum RedisCacheError {
30 #[error(transparent)]
32 Cache(#[from] CacheError),
33
34 #[error(transparent)]
36 Redis(#[from] redis::RedisError),
37
38 #[error("{}", json_message(.0))]
43 Json(#[from] serde_json::Error),
44}
45
46pub 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 #[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}