1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use serde_derive::Deserialize;
use serde_derive::Serialize;
#[derive(Debug)]
pub enum Error {
ParseError(String),
Rpc(RpcError),
Timeout,
VersionMismatch,
IdMismatch,
Json(serde_json::Error),
FailedRetry,
HttpError(http_types::Error),
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Self::Json(e)
}
}
impl From<http_types::Error> for Error {
fn from(e: http_types::Error) -> Self {
Self::HttpError(e)
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RpcError {
code: i32,
message: String,
data: Option<serde_json::Value>,
}
#[derive(Debug)]
pub enum RpcErrorTypes {
ParseError,
InvalidRequest,
MethodNotFound,
InvalidParams,
InternalError,
}
impl RpcError {
pub fn from_error_type(error: RpcErrorTypes, data: Option<serde_json::Value>) -> Self {
match error {
RpcErrorTypes::ParseError => Self {
code: -32700,
message: "Parse Error".to_owned(),
data,
},
RpcErrorTypes::InvalidRequest => Self {
code: -32600,
message: "Invalid Request".to_owned(),
data,
},
RpcErrorTypes::MethodNotFound => Self {
code: -32601,
message: "Method Not Found".to_owned(),
data,
},
RpcErrorTypes::InvalidParams => Self {
code: -32602,
message: "Invalid Params".to_owned(),
data,
},
RpcErrorTypes::InternalError => Self {
code: -32603,
message: "Internal Error".to_owned(),
data,
},
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Error::ParseError(ref e) => write!(f, "Parse Error: {}", e),
Error::Rpc(ref e) => write!(f, "RPC Error: {}", e.message),
Error::Timeout => write!(f, "Timeout error"),
Error::VersionMismatch => write!(f, "Version Mistmatch"),
Error::IdMismatch => write!(f, "ID Mismatch"),
Error::Json(ref e) => write!(f, "JSON Error: {}", e),
Error::FailedRetry => write!(f, "Failed Retry"),
Error::HttpError(ref e) => write!(f, "HTTP Error: {}", e),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
Error::ParseError(_) => None,
Error::Rpc(_) => None,
Error::Timeout => None,
Error::VersionMismatch => None,
Error::IdMismatch => None,
Error::Json(ref e) => Some(e),
Error::FailedRetry => None,
Error::HttpError(_) => None,
}
}
}