diff options
Diffstat (limited to 'jsonrpc/src/message.rs')
-rw-r--r-- | jsonrpc/src/message.rs | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/jsonrpc/src/message.rs b/jsonrpc/src/message.rs index 36ece38..deb5d77 100644 --- a/jsonrpc/src/message.rs +++ b/jsonrpc/src/message.rs @@ -1,5 +1,7 @@ use serde::{Deserialize, Serialize}; +use crate::RPCError; + pub type ID = u64; pub const JSONRPC_VERSION: &str = "2.0"; @@ -22,6 +24,8 @@ pub const INTERNAL_ERROR_CODE: i32 = -32603; /// SubscriptionID is used to identify a subscription. pub type SubscriptionID = u32; +pub const INTERNAL_ERROR_MSG: &str = "Internal error"; + /// Request represents a JSON-RPC request message. /// It includes the JSON-RPC version, an identifier for the request, the method /// to be invoked, and optional parameters. @@ -131,3 +135,57 @@ impl std::fmt::Display for Notification { ) } } + +impl Default for Response { + fn default() -> Self { + Self { + jsonrpc: JSONRPC_VERSION.to_string(), + error: None, + id: None, + result: None, + } + } +} + +impl RPCError { + pub fn to_response( + &self, + id: Option<serde_json::Value>, + data: Option<serde_json::Value>, + ) -> Response { + let err: Error = match self { + RPCError::ParseError(msg) => Error { + code: PARSE_ERROR_CODE, + message: msg.to_string(), + data, + }, + RPCError::InvalidParams(msg) => Error { + code: INVALID_PARAMS_ERROR_CODE, + message: msg.to_string(), + data, + }, + RPCError::InvalidRequest(msg) => Error { + code: INVALID_REQUEST_ERROR_CODE, + message: msg.to_string(), + data, + }, + RPCError::CustomError(code, msg) => Error { + code: *code, + message: msg.to_string(), + data, + }, + RPCError::InternalError => Error { + code: INTERNAL_ERROR_CODE, + message: INTERNAL_ERROR_MSG.to_string(), + data, + }, + }; + + Response { + jsonrpc: JSONRPC_VERSION.to_string(), + error: Some(err), + result: None, + id, + } + } +} |