From 5064133f1f59be9539ff6a2ebd830132b2379564 Mon Sep 17 00:00:00 2001 From: hozan23 Date: Sat, 15 Jun 2024 00:02:19 +0200 Subject: jsonrpc: separate the RPC errors from the library implementation errors --- jsonrpc/src/message.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) (limited to 'jsonrpc/src/message.rs') 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, + data: Option, + ) -> 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, + } + } +} -- cgit v1.2.3