borrowscope_runtime/
error.rs1use std::fmt;
6use std::io;
7
8#[derive(Debug)]
10pub enum Error {
11 SerializationError(serde_json::Error),
13 IoError(io::Error),
15 ExportError(String),
17 InvalidEventSequence(String),
19 LockError,
21}
22
23impl fmt::Display for Error {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 match self {
26 Error::SerializationError(e) => write!(f, "Serialization error: {}", e),
27 Error::IoError(e) => write!(f, "I/O error: {}", e),
28 Error::ExportError(msg) => write!(f, "Export error: {}", msg),
29 Error::InvalidEventSequence(msg) => write!(f, "Invalid event sequence: {}", msg),
30 Error::LockError => write!(f, "Failed to acquire lock"),
31 }
32 }
33}
34
35impl std::error::Error for Error {
36 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
37 match self {
38 Error::SerializationError(e) => Some(e),
39 Error::IoError(e) => Some(e),
40 _ => None,
41 }
42 }
43}
44
45impl From<serde_json::Error> for Error {
46 fn from(err: serde_json::Error) -> Self {
47 Error::SerializationError(err)
48 }
49}
50
51impl From<io::Error> for Error {
52 fn from(err: io::Error) -> Self {
53 Error::IoError(err)
54 }
55}
56
57pub type BorrowScopeResult<T> = std::result::Result<T, Error>;
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn test_error_display() {
66 let err = Error::LockError;
67 assert_eq!(err.to_string(), "Failed to acquire lock");
68
69 let err = Error::ExportError("test".to_string());
70 assert_eq!(err.to_string(), "Export error: test");
71
72 let err = Error::InvalidEventSequence("invalid".to_string());
73 assert_eq!(err.to_string(), "Invalid event sequence: invalid");
74 }
75
76 #[test]
77 fn test_error_from_serde() {
78 let json_err = serde_json::from_str::<i32>("invalid").unwrap_err();
79 let err: Error = json_err.into();
80 assert!(matches!(err, Error::SerializationError(_)));
81 }
82
83 #[test]
84 fn test_error_source_trait() {
85 use std::error::Error as StdError;
86
87 let json_err = serde_json::from_str::<i32>("invalid").unwrap_err();
88 let err = Error::SerializationError(json_err);
89 assert!(StdError::source(&err).is_some());
90
91 let err = Error::LockError;
92 assert!(StdError::source(&err).is_none());
93 }
94}