@@ -13,8 +13,27 @@ use serde_json;
13
13
14
14
use std:: convert:: TryFrom ;
15
15
use std:: convert:: TryInto ;
16
+ use std:: error:: Error ;
17
+ use std:: fmt;
16
18
use std:: sync:: atomic:: { AtomicUsize , Ordering } ;
17
19
20
+ /// An error returned by the RPC server.
21
+ #[ derive( Debug ) ]
22
+ pub struct RpcError {
23
+ /// The error code.
24
+ pub code : i64 ,
25
+ /// The error message.
26
+ pub message : String ,
27
+ }
28
+
29
+ impl fmt:: Display for RpcError {
30
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
31
+ write ! ( f, "RPC error {}: {}" , self . code, self . message)
32
+ }
33
+ }
34
+
35
+ impl Error for RpcError { }
36
+
18
37
/// A simple RPC client for calling methods using HTTP `POST`.
19
38
pub struct RpcClient {
20
39
basic_auth : String ,
@@ -68,9 +87,11 @@ impl RpcClient {
68
87
69
88
let error = & response[ "error" ] ;
70
89
if !error. is_null ( ) {
71
- // TODO: Examine error code for a more precise std::io::ErrorKind.
72
- let message = error[ "message" ] . as_str ( ) . unwrap_or ( "unknown error" ) ;
73
- return Err ( std:: io:: Error :: new ( std:: io:: ErrorKind :: Other , message) ) ;
90
+ let rpc_error = RpcError {
91
+ code : error[ "code" ] . as_i64 ( ) . unwrap_or ( -1 ) ,
92
+ message : error[ "message" ] . as_str ( ) . unwrap_or ( "unknown error" ) . to_string ( )
93
+ } ;
94
+ return Err ( std:: io:: Error :: new ( std:: io:: ErrorKind :: Other , rpc_error) ) ;
74
95
}
75
96
76
97
let result = & mut response[ "result" ] ;
@@ -163,7 +184,9 @@ mod tests {
163
184
match client. call_method :: < u64 > ( "getblock" , & [ invalid_block_hash] ) . await {
164
185
Err ( e) => {
165
186
assert_eq ! ( e. kind( ) , std:: io:: ErrorKind :: Other ) ;
166
- assert_eq ! ( e. get_ref( ) . unwrap( ) . to_string( ) , "invalid parameter" ) ;
187
+ let rpc_error: Box < RpcError > = e. into_inner ( ) . unwrap ( ) . downcast ( ) . unwrap ( ) ;
188
+ assert_eq ! ( rpc_error. code, -8 ) ;
189
+ assert_eq ! ( rpc_error. message, "invalid parameter" ) ;
167
190
} ,
168
191
Ok ( _) => panic ! ( "Expected error" ) ,
169
192
}
0 commit comments