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