Skip to main content

hive_rs/
error.rs

1use serde_json::Value;
2use thiserror::Error;
3
4#[derive(Debug, Error)]
5pub enum HiveError {
6    #[error("RPC error {code}: {message}")]
7    Rpc {
8        code: i64,
9        message: String,
10        data: Option<Value>,
11    },
12
13    #[error("Transport error: {0}")]
14    Transport(String),
15
16    #[error("Serialization error: {0}")]
17    Serialization(String),
18
19    #[error("Invalid key: {0}")]
20    InvalidKey(String),
21
22    #[error("Signing error: {0}")]
23    Signing(String),
24
25    #[error("All nodes failed")]
26    AllNodesFailed,
27
28    #[error("Request timed out")]
29    Timeout,
30
31    #[error("Invalid asset: {0}")]
32    InvalidAsset(String),
33
34    #[error("{0}")]
35    Other(String),
36}
37
38pub type Result<T> = std::result::Result<T, HiveError>;
39
40impl From<reqwest::Error> for HiveError {
41    fn from(value: reqwest::Error) -> Self {
42        if value.is_timeout() {
43            Self::Timeout
44        } else {
45            Self::Transport(value.to_string())
46        }
47    }
48}
49
50impl From<serde_json::Error> for HiveError {
51    fn from(value: serde_json::Error) -> Self {
52        Self::Serialization(value.to_string())
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::HiveError;
59
60    #[test]
61    fn error_variants_display() {
62        let samples = vec![
63            HiveError::Rpc {
64                code: -32000,
65                message: "boom".to_string(),
66                data: None,
67            },
68            HiveError::Transport("io".to_string()),
69            HiveError::Serialization("bad json".to_string()),
70            HiveError::InvalidKey("bad key".to_string()),
71            HiveError::Signing("failed".to_string()),
72            HiveError::AllNodesFailed,
73            HiveError::Timeout,
74            HiveError::InvalidAsset("bad amount".to_string()),
75            HiveError::Other("other".to_string()),
76        ];
77
78        for err in samples {
79            assert!(!err.to_string().is_empty());
80        }
81    }
82}