1use std::error::Error;
2use std::fmt;
3
4#[derive(Debug, Clone)]
6pub enum RullstError {
7 RecordNotFound,
9 DatabaseError(String),
11 SerializationError(String),
13 CacheError(String),
15 Validation(String),
17 Internal(String),
19}
20
21impl fmt::Display for RullstError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 match self {
24 RullstError::RecordNotFound => write!(f, "Record not found"),
25 RullstError::DatabaseError(msg) => write!(f, "Database error: {}", msg),
26 RullstError::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
27 RullstError::CacheError(msg) => write!(f, "Cache error: {}", msg),
28 RullstError::Validation(msg) => write!(f, "Validation error: {}", msg),
29 RullstError::Internal(msg) => write!(f, "Internal error: {}", msg),
30 }
31 }
32}
33
34impl Error for RullstError {}
35
36impl From<sqlx::Error> for RullstError {
37 fn from(err: sqlx::Error) -> Self {
38 match err {
39 sqlx::Error::RowNotFound => RullstError::RecordNotFound,
40 _ => RullstError::DatabaseError(err.to_string()),
41 }
42 }
43}
44
45impl From<serde_json::Error> for RullstError {
46 fn from(err: serde_json::Error) -> Self {
47 RullstError::SerializationError(err.to_string())
48 }
49}
50
51#[cfg(feature = "redis")]
52impl From<redis::RedisError> for RullstError {
53 fn from(err: redis::RedisError) -> Self {
54 RullstError::CacheError(err.to_string())
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_rullst_error_display() {
64 assert_eq!(RullstError::RecordNotFound.to_string(), "Record not found");
65 assert_eq!(
66 RullstError::DatabaseError("msg".to_string()).to_string(),
67 "Database error: msg"
68 );
69 assert_eq!(
70 RullstError::SerializationError("msg".to_string()).to_string(),
71 "Serialization error: msg"
72 );
73 assert_eq!(
74 RullstError::Validation("msg".to_string()).to_string(),
75 "Validation error: msg"
76 );
77 assert_eq!(
78 RullstError::Internal("msg".to_string()).to_string(),
79 "Internal error: msg"
80 );
81 }
82
83 #[test]
84 fn test_rullst_error_from() {
85 let sqlx_err = sqlx::Error::RowNotFound;
86 let err: RullstError = sqlx_err.into();
87 assert!(matches!(err, RullstError::RecordNotFound));
88 }
89}