aboutsummaryrefslogtreecommitdiff
path: root/jsonrpc/src/message.rs
diff options
context:
space:
mode:
authorhozan23 <hozan23@karyontech.net>2024-06-15 00:02:19 +0200
committerhozan23 <hozan23@karyontech.net>2024-06-15 00:02:19 +0200
commit5064133f1f59be9539ff6a2ebd830132b2379564 (patch)
tree3722421bea0b3dd21137f9abc98e3e6c950d76d8 /jsonrpc/src/message.rs
parent3429caa87699d986f799a11f6e0f4526e723b655 (diff)
jsonrpc: separate the RPC errors from the library implementation errors
Diffstat (limited to 'jsonrpc/src/message.rs')
-rw-r--r--jsonrpc/src/message.rs58
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,
+ }
+ }
+}