eth_jsonrpc_lib/
error.rs

1// Copyright Rivtower Technologies LLC.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! jsonrpc errors
16
17use serde::de::{Deserialize, Deserializer};
18use serde::ser::{Serialize, Serializer};
19use serde_json::{self, Value};
20
21/// JSONRPC error code
22#[derive(Debug, PartialEq, Clone)]
23pub enum ErrorCode {
24    /// Invalid JSON was received by the server.
25    /// An error occurred on the server while parsing the JSON text.
26    ParseError,
27    /// The JSON sent is not a valid Request object.
28    InvalidRequest,
29    /// The method does not exist / is not available.
30    MethodNotFound,
31    /// Invalid method parameter(s).
32    InvalidParams,
33    /// Internal JSON-RPC error.
34    InternalError,
35    /// Reserved for implementation-defined server-errors.
36    ServerError(i64),
37    ///-32003             查询类错误
38    QueryError,
39    ///-32006             交易认证类错误
40    TxAuthError,
41    ///-32099             请求超时
42    TimeOut,
43    ///-34001             wrap orign to etherum type error
44    WrapTypeError,
45    ///-34002             grpc interface error
46    GrpcError,
47}
48
49impl ErrorCode {
50    /// Returns integer code value
51    pub fn code(&self) -> i64 {
52        match *self {
53            ErrorCode::ParseError => -32_700,
54            ErrorCode::InvalidRequest => -32_600,
55            ErrorCode::MethodNotFound => -32_601,
56            ErrorCode::InvalidParams => -32_602,
57            ErrorCode::InternalError => -32_603,
58            ErrorCode::ServerError(code) => code,
59            ErrorCode::QueryError => -32_003,
60            ErrorCode::TxAuthError => -32_006,
61            ErrorCode::TimeOut => -32_099,
62            ErrorCode::WrapTypeError => -34_001,
63            ErrorCode::GrpcError => -34_002,
64        }
65    }
66
67    /// Returns human-readable description
68    pub fn description(&self) -> String {
69        let desc = match *self {
70            ErrorCode::ParseError => "Parse error",
71            ErrorCode::InvalidRequest => "Invalid request",
72            ErrorCode::MethodNotFound => "Method not found",
73            ErrorCode::InvalidParams => "Invalid params",
74            ErrorCode::InternalError => "Internal error",
75            ErrorCode::ServerError(_) => "Server error",
76            ErrorCode::QueryError => "Query error",
77            ErrorCode::TxAuthError => "Tx auth error",
78            ErrorCode::TimeOut => "Time out",
79            ErrorCode::WrapTypeError => "Wrap type error",
80            ErrorCode::GrpcError => "Grpc error",
81        };
82        desc.to_string()
83    }
84}
85
86impl<'a> Deserialize<'a> for ErrorCode {
87    fn deserialize<D>(deserializer: D) -> Result<ErrorCode, D::Error>
88    where
89        D: Deserializer<'a>,
90    {
91        let v: Value = Deserialize::deserialize(deserializer)?;
92        match v.as_i64() {
93            Some(-32_700) => Ok(ErrorCode::ParseError),
94            Some(-32_600) => Ok(ErrorCode::InvalidRequest),
95            Some(-32_601) => Ok(ErrorCode::MethodNotFound),
96            Some(-32_602) => Ok(ErrorCode::InvalidParams),
97            Some(-32_603) => Ok(ErrorCode::InternalError),
98            Some(-32_003) => Ok(ErrorCode::QueryError),
99            Some(-32_006) => Ok(ErrorCode::TxAuthError),
100            Some(-32_099) => Ok(ErrorCode::TimeOut),
101            Some(-34_001) => Ok(ErrorCode::WrapTypeError),
102            Some(-34_002) => Ok(ErrorCode::GrpcError),
103            Some(code) => Ok(ErrorCode::ServerError(code)),
104            _ => unreachable!(),
105        }
106    }
107}
108
109impl Serialize for ErrorCode {
110    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
111    where
112        S: Serializer,
113    {
114        serializer.serialize_i64(self.code())
115    }
116}
117
118/// Error object as defined in Spec
119#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
120pub struct Error {
121    /// Code
122    pub code: ErrorCode,
123    /// Message
124    pub message: String,
125    /// Optional data
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub data: Option<Value>,
128}
129
130impl Error {
131    /// Wraps given `ErrorCode`
132    pub fn new(code: ErrorCode) -> Self {
133        Error {
134            message: code.description(),
135            code,
136            data: None,
137        }
138    }
139
140    /// Creates new `ParseError`
141    pub fn parse_error() -> Self {
142        Self::new(ErrorCode::ParseError)
143    }
144
145    /// Creates new `InvalidRequest`
146    pub fn invalid_request() -> Self {
147        Self::new(ErrorCode::InvalidRequest)
148    }
149
150    /// Creates new `MethodNotFound`
151    pub fn method_not_found() -> Self {
152        Self::new(ErrorCode::MethodNotFound)
153    }
154
155    /// Creates new `InvalidParams`
156    pub fn invalid_params<M>(message: M) -> Self
157    where
158        M: Into<String>,
159    {
160        Error {
161            code: ErrorCode::InvalidParams,
162            message: message.into(),
163            data: None,
164        }
165    }
166
167    /// Creates new `InternalError`
168    pub fn internal_error() -> Self {
169        Self::new(ErrorCode::InternalError)
170    }
171
172    /// Creates new `InvalidRequest` with invalid version description
173    pub fn invalid_version() -> Self {
174        Error {
175            code: ErrorCode::InvalidRequest,
176            message: "Unsupported JSON-RPC protocol version".to_owned(),
177            data: None,
178        }
179    }
180
181    pub fn server_error<M>(err_code: i64, message: M) -> Self
182    where
183        M: Into<String>,
184    {
185        Error {
186            code: ErrorCode::ServerError(err_code),
187            message: message.into(),
188            data: None,
189        }
190    }
191
192    pub fn parse_error_with_message<M>(message: M) -> Self
193    where
194        M: Into<String>,
195    {
196        Error {
197            code: ErrorCode::ParseError,
198            message: message.into(),
199            data: None,
200        }
201    }
202
203    /// Creates new `InvalidParams`
204    pub fn invalid_params_len() -> Self {
205        Error {
206            code: ErrorCode::InvalidParams,
207            message: "Invalid JSON-RPC params length".to_owned(),
208            data: None,
209        }
210    }
211
212    pub fn query_error() -> Self {
213        Self::new(ErrorCode::QueryError)
214    }
215
216    pub fn tx_auth_error() -> Self {
217        Self::new(ErrorCode::TxAuthError)
218    }
219
220    pub fn time_out() -> Self {
221        Self::new(ErrorCode::TimeOut)
222    }
223
224    pub fn wrap_type_error() -> Self {
225        Self::new(ErrorCode::WrapTypeError)
226    }
227
228    pub fn grpc_error() -> Self {
229        Self::new(ErrorCode::GrpcError)
230    }
231}
232
233impl From<serde_json::Error> for Error {
234    fn from(err: serde_json::Error) -> Error {
235        Error {
236            code: ErrorCode::ParseError,
237            message: err.to_string(),
238            data: None,
239        }
240    }
241}