1use thiserror::Error;
10
11#[derive(Debug, Error)]
16pub enum CommonError {
17 #[error("invalid argument: {0}")]
19 InvalidArgument(String),
20
21 #[error("value out of range: {0}")]
23 OutOfRange(String),
24
25 #[error("borsh (de)serialization error: {0}")]
27 Borsh(String),
28
29 #[error("json (de)serialization error: {0}")]
31 Json(String),
32
33 #[error("toml parse error: {0}")]
35 Toml(String),
36
37 #[error("config error: {0}")]
39 Config(String),
40
41 #[error("io error: {0}")]
43 Io(#[from] std::io::Error),
44}
45
46impl From<serde_json::Error> for CommonError {
51 fn from(e: serde_json::Error) -> Self {
52 CommonError::Json(e.to_string())
53 }
54}
55
56pub type Result<T, E = CommonError> = std::result::Result<T, E>;
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn display_messages_include_context() {
65 let e = CommonError::InvalidArgument("x must be positive".into());
66 assert_eq!(e.to_string(), "invalid argument: x must be positive");
67 }
68
69 #[test]
70 fn out_of_range_formats() {
71 let e = CommonError::OutOfRange("height > u64::MAX".into());
72 assert!(e.to_string().contains("out of range"));
73 }
74
75 #[test]
76 fn io_error_conversion() {
77 let io = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
78 let e: CommonError = io.into();
79 assert!(matches!(e, CommonError::Io(_)));
80 }
81}