From 7086ccffc32089d2197e0011b5f85c4516fca800 Mon Sep 17 00:00:00 2001 From: PiRK Date: Sat, 21 Dec 2024 08:57:50 +0100 Subject: [PATCH 1/2] use String for RPCError This enables uses cases that require serving error messages built with runtime data such as ``` RPCError::InvalidParamsString(format!("Method {method_name} requires {num_required} params, got {num_actual}")) ``` ``` // Forward error message RPCError::CustomErrorString(1, err.what().to_string()) ``` --- jsonrpc/src/error.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jsonrpc/src/error.rs b/jsonrpc/src/error.rs index 092ac7f2..87d3ac5e 100644 --- a/jsonrpc/src/error.rs +++ b/jsonrpc/src/error.rs @@ -79,13 +79,13 @@ pub type RPCResult = std::result::Result; #[derive(ThisError, Debug)] pub enum RPCError { #[error("Custom Error: code: {0} msg: {1}")] - CustomError(i32, &'static str), + CustomError(i32, String), #[error("Invalid Params: {0}")] - InvalidParams(&'static str), + InvalidParams(String), #[error("Invalid Request: {0}")] - InvalidRequest(&'static str), + InvalidRequest(String), #[error("Parse Error: {0}")] ParseError(String), From 7529856c193e6354fb7197dce8268ecb41de99c2 Mon Sep 17 00:00:00 2001 From: PiRK Date: Mon, 30 Dec 2024 13:17:00 +0100 Subject: [PATCH 2/2] use String for all errors --- core/src/crypto/key_pair.rs | 4 ++-- core/src/error.rs | 4 ++-- core/src/util/path.rs | 2 +- jsonrpc/src/client/message_dispatcher.rs | 4 ++-- jsonrpc/src/client/mod.rs | 8 ++++---- jsonrpc/src/client/subscriptions.rs | 4 ++-- jsonrpc/src/error.rs | 4 ++-- p2p/src/discovery/lookup.rs | 4 +++- p2p/src/error.rs | 4 ++-- 9 files changed, 20 insertions(+), 18 deletions(-) diff --git a/core/src/crypto/key_pair.rs b/core/src/crypto/key_pair.rs index a7a8eafb..68f5f8cf 100644 --- a/core/src/crypto/key_pair.rs +++ b/core/src/crypto/key_pair.rs @@ -122,7 +122,7 @@ impl Ed25519PublicKey { pub fn from_bytes(pk: &[u8]) -> Result { let pk_bytes: [u8; 32] = pk .try_into() - .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 32]"))?; + .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 32]".to_string()))?; Ok(Self(ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)?)) } @@ -136,7 +136,7 @@ impl PublicKeyExt for Ed25519PublicKey { fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()> { let sig_bytes: [u8; 64] = signature .try_into() - .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 64]"))?; + .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 64]".to_string()))?; self.0 .verify(msg, &ed25519_dalek::Signature::from_bytes(&sig_bytes))?; Ok(()) diff --git a/core/src/error.rs b/core/src/error.rs index 754feb56..6f324173 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -8,13 +8,13 @@ pub enum Error { IO(#[from] std::io::Error), #[error("TryInto Error: {0}")] - TryInto(&'static str), + TryInto(String), #[error("Timeout Error")] Timeout, #[error("Path Not Found Error: {0}")] - PathNotFound(&'static str), + PathNotFound(String), #[error("Event Emit Error: {0}")] EventEmitError(String), diff --git a/core/src/util/path.rs b/core/src/util/path.rs index 2cd900a3..1f930a4b 100644 --- a/core/src/util/path.rs +++ b/core/src/util/path.rs @@ -5,7 +5,7 @@ use crate::{error::Error, Result}; /// Returns the user's home directory as a `PathBuf`. #[allow(dead_code)] pub fn home_dir() -> Result { - dirs::home_dir().ok_or(Error::PathNotFound("Home dir not found")) + dirs::home_dir().ok_or(Error::PathNotFound("Home dir not found".to_string())) } /// Expands a tilde (~) in a path and returns the expanded `PathBuf`. diff --git a/jsonrpc/src/client/message_dispatcher.rs b/jsonrpc/src/client/message_dispatcher.rs index 8ec3fefe..e87a7ba1 100644 --- a/jsonrpc/src/client/message_dispatcher.rs +++ b/jsonrpc/src/client/message_dispatcher.rs @@ -54,14 +54,14 @@ impl MessageDispatcher { let res_id = match res.id { Some(ref rid) => rid.clone(), None => { - return Err(Error::InvalidMsg("Response id is none")); + return Err(Error::InvalidMsg("Response id is none".to_string())); } }; let id: RequestID = serde_json::from_value(res_id)?; let val = self.chans.lock().await.remove(&id); match val { Some(tx) => tx.send(res).await.map_err(Error::from), - None => Err(Error::InvalidMsg("Receive unknown message")), + None => Err(Error::InvalidMsg("Receive unknown message".to_string())), } } } diff --git a/jsonrpc/src/client/mod.rs b/jsonrpc/src/client/mod.rs index 2127f8f3..e7b55dca 100644 --- a/jsonrpc/src/client/mod.rs +++ b/jsonrpc/src/client/mod.rs @@ -90,7 +90,7 @@ where match response.result { Some(result) => Ok(serde_json::from_value::(result)?), - None => Err(Error::InvalidMsg("Invalid response result")), + None => Err(Error::InvalidMsg("Invalid response result".to_string())), } } @@ -108,7 +108,7 @@ where let sub_id = match response.result { Some(result) => serde_json::from_value::(result)?, - None => return Err(Error::InvalidMsg("Invalid subscription id")), + None => return Err(Error::InvalidMsg("Invalid subscription id".to_string())), }; let sub = self.subscriptions.subscribe(sub_id).await; @@ -172,7 +172,7 @@ where // It should be OK to unwrap here, as the message dispatcher checks // for the response id. if *response.id.as_ref().expect("Get response id") != id { - return Err(Error::InvalidMsg("Invalid response id")); + return Err(Error::InvalidMsg("Invalid response id".to_string())); } Ok(response) @@ -325,7 +325,7 @@ where }, Err(err) => { error!("Receive unexpected msg {msg}: {err}"); - Err(Error::InvalidMsg("Unexpected msg")) + Err(Error::InvalidMsg("Unexpected msg".to_string())) } } } diff --git a/jsonrpc/src/client/subscriptions.rs b/jsonrpc/src/client/subscriptions.rs index 8cecd19c..01162d1b 100644 --- a/jsonrpc/src/client/subscriptions.rs +++ b/jsonrpc/src/client/subscriptions.rs @@ -87,13 +87,13 @@ impl Subscriptions { pub(super) async fn notify(&self, nt: Notification) -> Result<()> { let nt_res: NotificationResult = match nt.params { Some(ref p) => serde_json::from_value(p.clone())?, - None => return Err(Error::InvalidMsg("Invalid notification msg")), + None => return Err(Error::InvalidMsg("Invalid notification msg".to_string())), }; match self.subs.lock().await.get(&nt_res.subscription) { Some(s) => s.notify(nt_res.result.unwrap_or(json!(""))).await?, None => { - return Err(Error::InvalidMsg("Unknown notification")); + return Err(Error::InvalidMsg("Unknown notification".to_string())); } } diff --git a/jsonrpc/src/error.rs b/jsonrpc/src/error.rs index 87d3ac5e..596064f3 100644 --- a/jsonrpc/src/error.rs +++ b/jsonrpc/src/error.rs @@ -21,7 +21,7 @@ pub enum Error { Decode(String), #[error("Invalid Message Error: {0}")] - InvalidMsg(&'static str), + InvalidMsg(String), #[error(transparent)] ParseJSON(#[from] serde_json::Error), @@ -58,7 +58,7 @@ pub enum Error { WebSocket(#[from] async_tungstenite::tungstenite::Error), #[error("Unexpected Error: {0}")] - General(&'static str), + General(String), #[error(transparent)] KaryonCore(#[from] karyon_core::error::Error), diff --git a/p2p/src/discovery/lookup.rs b/p2p/src/discovery/lookup.rs index 0b278c79..2e461c5b 100644 --- a/p2p/src/discovery/lookup.rs +++ b/p2p/src/discovery/lookup.rs @@ -279,7 +279,9 @@ impl LookupService { NetMsgCmd::Peers => { peers = decode::(&msg.payload)?.0.peers; if peers.len() >= MAX_PEERS_IN_PEERSMSG { - return Err(Error::Lookup("Received too many peers in PeersMsg")); + return Err(Error::Lookup( + "Received too many peers in PeersMsg".to_string(), + )); } break; } diff --git a/p2p/src/error.rs b/p2p/src/error.rs index 7270052e..a154f457 100644 --- a/p2p/src/error.rs +++ b/p2p/src/error.rs @@ -57,10 +57,10 @@ pub enum Error { InvalidPongMsg, #[error("Discovery error: {0}")] - Discovery(&'static str), + Discovery(String), #[error("Lookup error: {0}")] - Lookup(&'static str), + Lookup(String), #[error("Peer Already Connected")] PeerAlreadyConnected,