Skip to content

Commit c12db80

Browse files
authored
Remove thiserror and use more specific Error names (#419)
* small result clean up * lets not overcomplicate * remove thiserror * remove unused errors
1 parent 6343099 commit c12db80

File tree

8 files changed

+33
-132
lines changed

8 files changed

+33
-132
lines changed

Cargo.lock

Lines changed: 1 addition & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,12 @@ members = [
2020
[dependencies]
2121
# crates.io no_std
2222
codec = { package = "parity-scale-codec", version = "3.2.1", default-features = false, features = ['derive'] }
23+
derive_more = { version = "0.99.5" }
2324
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
2425
log = { version = "0.4.14", default-features = false }
2526
serde = { version = "1.0.136", default-features = false, features = ["derive"] }
2627
serde_json = { version = "1.0.79", default-features = false }
2728

28-
#FIXME: convert back to thiserror once possible #317
29-
thiserror = { version = "1.0", package = "thiserror-core", default-features = false }
30-
3129
# crates.io std only
3230
url = { version = "2.0.0", optional = true }
3331

@@ -69,7 +67,6 @@ std = [
6967
"log/std",
7068
"serde/std",
7169
"serde_json/std",
72-
"thiserror/std",
7370
# crates.io std only
7471
"url",
7572
# substrate no_std

src/api/api_client.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ where
243243
fn get_genesis_hash(client: &Client) -> Result<Runtime::Hash> {
244244
let genesis: Option<Runtime::Hash> =
245245
client.request("chain_getBlockHash", rpc_params![Some(0)])?;
246-
genesis.ok_or(Error::Genesis)
246+
genesis.ok_or(Error::FetchGenesisHash)
247247
}
248248

249249
/// Get runtime version from node via websocket query.

src/api/error.rs

Lines changed: 4 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -24,70 +24,21 @@ use alloc::{boxed::Box, string::String};
2424

2525
pub type Result<T> = core::result::Result<T, Error>;
2626

27-
#[derive(Debug, thiserror::Error)]
27+
#[derive(Debug, derive_more::From)]
2828
pub enum Error {
29-
#[error("Fetching genesis hash failed. Are you connected to the correct endpoint?")]
30-
Genesis,
31-
#[error("Fetching runtime version failed. Are you connected to the correct endpoint?")]
32-
RuntimeVersion,
33-
#[error("Fetching Metadata failed. Are you connected to the correct endpoint?")]
34-
MetadataFetch,
35-
#[error("Operation needs a signer to be set in the api")]
29+
FetchGenesisHash,
3630
NoSigner,
37-
#[error("RpcClient error: {0:?}")]
38-
RpcClient(#[from] RpcClientError),
39-
#[error("Metadata Error: {0:?}")]
31+
RpcClient(RpcClientError),
4032
Metadata(MetadataError),
41-
#[error("InvalidMetadata: {0:?}")]
4233
InvalidMetadata(InvalidMetadataError),
43-
#[error("Events Error: {0:?}")]
4434
NodeApi(ac_node_api::error::Error),
45-
#[error("Error decoding storage value: {0}")]
4635
StorageValueDecode(codec::Error),
47-
#[error("UnsupportedXtStatus Error: Can only wait for finalized, in block, broadcast and ready. Waited for: {0:?}")]
4836
UnsupportedXtStatus(XtStatus),
49-
#[error("Error converting NumberOrHex to Balance")]
5037
TryFromIntError,
51-
#[error("The node runtime could not dispatch an extrinsic")]
5238
Dispatch(DispatchError),
53-
#[error("Extrinsic Error: {0}")]
5439
Extrinsic(String),
55-
#[error("Stream ended unexpectedly")]
5640
NoStream,
57-
#[error("Expected a block hash")]
5841
NoBlockHash,
59-
#[error("Did not find any block")]
6042
NoBlock,
61-
#[error(transparent)]
62-
Other(#[from] Box<dyn core::error::Error + Send + Sync + 'static>),
63-
}
64-
65-
impl From<codec::Error> for Error {
66-
fn from(error: codec::Error) -> Self {
67-
Error::StorageValueDecode(error)
68-
}
69-
}
70-
71-
impl From<InvalidMetadataError> for Error {
72-
fn from(error: InvalidMetadataError) -> Self {
73-
Error::InvalidMetadata(error)
74-
}
75-
}
76-
77-
impl From<MetadataError> for Error {
78-
fn from(error: MetadataError) -> Self {
79-
Error::Metadata(error)
80-
}
81-
}
82-
83-
impl From<ac_node_api::error::Error> for Error {
84-
fn from(error: ac_node_api::error::Error) -> Self {
85-
Error::NodeApi(error)
86-
}
87-
}
88-
89-
impl From<ac_node_api::error::DispatchError> for Error {
90-
fn from(error: ac_node_api::error::DispatchError) -> Self {
91-
Error::Dispatch(error)
92-
}
43+
Other(Box<dyn core::error::Error + Send + Sync + 'static>),
9344
}

src/rpc/error.rs

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,21 @@ use alloc::{boxed::Box, string::String};
1919

2020
pub type Result<T> = core::result::Result<T, Error>;
2121

22-
#[derive(Debug, thiserror::Error)]
22+
#[derive(Debug)]
2323
pub enum Error {
24-
#[error("Serde json error: {0}")]
25-
Serde(serde_json::error::Error),
26-
#[error("mpsc send Error: {0}")]
27-
Send(String),
28-
#[error("Could not convert to valid Url: {0}")]
29-
Url(String),
30-
#[error("ChannelReceiveError, sender is disconnected: {0}")]
31-
ChannelDisconnected(String),
32-
#[error("Failure during thread creation: {0}")]
24+
SerdeJson(serde_json::error::Error),
25+
MpscSend(String),
26+
InvalidUrl(String),
27+
RecvError(String),
3328
Io(String),
34-
#[error("Exceeded maximum amount of connections")]
35-
ConnectionAttemptsExceeded,
36-
#[error("Websocket Connection was closed unexpectedly")]
29+
MaxConnectionAttemptsExceeded,
3730
ConnectionClosed,
38-
#[error(transparent)]
39-
Client(#[from] Box<dyn core::error::Error + Send + Sync + 'static>),
31+
Client(Box<dyn core::error::Error + Send + Sync + 'static>),
4032
}
4133

4234
impl From<serde_json::error::Error> for Error {
4335
fn from(error: serde_json::error::Error) -> Self {
44-
Self::Serde(error)
36+
Self::SerdeJson(error)
4537
}
4638
}
4739

@@ -68,13 +60,13 @@ mod std_only {
6860

6961
impl From<SendError<String>> for Error {
7062
fn from(error: SendError<String>) -> Self {
71-
Self::Send(error.0)
63+
Self::MpscSend(error.0)
7264
}
7365
}
7466

7567
impl From<RecvError> for Error {
7668
fn from(error: RecvError) -> Self {
77-
Self::ChannelDisconnected(format!("{:?}", error))
69+
Self::RecvError(format!("{:?}", error))
7870
}
7971
}
8072

@@ -86,7 +78,7 @@ mod std_only {
8678

8779
impl From<url::ParseError> for Error {
8880
fn from(error: url::ParseError) -> Self {
89-
Self::Io(format!("{:?}", error))
81+
Self::InvalidUrl(format!("{:?}", error))
9082
}
9183
}
9284
}

src/rpc/tungstenite_client/client.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ fn subscribe_to_server(
141141
pub fn do_reconnect(error: &RpcClientError) -> bool {
142142
matches!(
143143
error,
144-
RpcClientError::Serde(_) | RpcClientError::ConnectionClosed | RpcClientError::Client(_)
144+
RpcClientError::SerdeJson(_) | RpcClientError::ConnectionClosed | RpcClientError::Client(_)
145145
)
146146
}
147147

@@ -173,7 +173,7 @@ fn attempt_connection_until(url: &Url, max_attempts: u8) -> Result<(MySocket, Re
173173
current_attempt += 1;
174174
}
175175

176-
Err(RpcClientError::ConnectionAttemptsExceeded)
176+
Err(RpcClientError::MaxConnectionAttemptsExceeded)
177177
}
178178

179179
fn read_until_text_message(socket: &mut MySocket) -> Result<String> {

src/rpc/ws_client/client.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ impl WsRpcClient {
8585
where
8686
MessageHandler: HandleMessage + Clone + Send + 'static,
8787
MessageHandler::ThreadMessage: Send + Sync + Debug,
88-
MessageHandler::Error: Into<ws::Error>,
8988
MessageHandler::Context: From<MessageContext<MessageHandler::ThreadMessage>>,
9089
{
9190
let mut socket = ws::Builder::new().build(move |out| RpcClient {
@@ -116,7 +115,6 @@ impl WsRpcClient {
116115
where
117116
MessageHandler: HandleMessage + Clone + Send + 'static,
118117
MessageHandler::ThreadMessage: Send + Sync + Debug,
119-
MessageHandler::Error: Into<ws::Error>,
120118
MessageHandler::Context: From<MessageContext<MessageHandler::ThreadMessage>>,
121119
{
122120
let (result_in, result_out) = channel();

src/rpc/ws_client/mod.rs

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -20,26 +20,19 @@ pub use ac_node_api::{events::EventDetails, StaticEvent};
2020
pub use client::WsRpcClient;
2121
use log::*;
2222
use std::{fmt::Debug, sync::mpsc::Sender as ThreadOut};
23-
use ws::{CloseCode, Handler, Handshake, Message, Sender};
23+
use ws::{CloseCode, Handler, Handshake, Message, Result as WsResult, Sender};
2424

2525
pub mod client;
2626
pub mod subscription;
2727

28-
type RpcResult<T> = Result<T, RpcClientError>;
29-
30-
pub type RpcMessage = RpcResult<String>;
28+
pub type RpcMessage = crate::rpc::Result<String>;
3129

3230
#[allow(clippy::result_large_err)]
3331
pub(crate) trait HandleMessage {
3432
type ThreadMessage;
35-
type Error;
3633
type Context;
37-
type Result;
3834

39-
fn handle_message(
40-
&self,
41-
context: &mut Self::Context,
42-
) -> core::result::Result<Self::Result, Self::Error>;
35+
fn handle_message(&self, context: &mut Self::Context) -> WsResult<()>;
4336
}
4437

4538
// Clippy says request is never used, even though it is..
@@ -62,27 +55,23 @@ pub(crate) struct RpcClient<MessageHandler, ThreadMessage> {
6255
impl<MessageHandler: HandleMessage> Handler
6356
for RpcClient<MessageHandler, MessageHandler::ThreadMessage>
6457
where
65-
MessageHandler::Error: Into<ws::Error>,
6658
MessageHandler::Context: From<MessageContext<MessageHandler::ThreadMessage>>,
6759
{
68-
fn on_open(&mut self, _: Handshake) -> Result<(), ws::Error> {
60+
fn on_open(&mut self, _: Handshake) -> WsResult<()> {
6961
info!("sending request: {}", self.request);
7062
self.out.send(self.request.clone())?;
7163
Ok(())
7264
}
7365

74-
fn on_message(&mut self, msg: Message) -> Result<(), ws::Error> {
66+
fn on_message(&mut self, msg: Message) -> WsResult<()> {
7567
let mut context: MessageHandler::Context = MessageContext {
7668
out: self.out.clone(),
7769
request: self.request.clone(),
7870
result: self.result.clone(),
7971
msg,
8072
}
8173
.into();
82-
self.message_handler
83-
.handle_message(&mut context)
84-
.map_err(|e| e.into())
85-
.map(|_| ())
74+
self.message_handler.handle_message(&mut context)
8675
}
8776
}
8877

@@ -91,11 +80,9 @@ pub(crate) struct RequestHandler;
9180

9281
impl HandleMessage for RequestHandler {
9382
type ThreadMessage = RpcMessage;
94-
type Error = ws::Error;
9583
type Context = MessageContext<Self::ThreadMessage>;
96-
type Result = ();
9784

98-
fn handle_message(&self, context: &mut Self::Context) -> Result<Self::Result, Self::Error> {
85+
fn handle_message(&self, context: &mut Self::Context) -> WsResult<()> {
9986
let result = &context.result;
10087
let out = &context.out;
10188
let msg = &context.msg;
@@ -106,11 +93,9 @@ impl HandleMessage for RequestHandler {
10693
info!("Got get_request_msg {}", msg);
10794
let result_str = serde_json::from_str(msg.as_text()?)
10895
.map(|v: serde_json::Value| v["result"].to_string())
109-
.map_err(RpcClientError::Serde);
96+
.map_err(RpcClientError::SerdeJson);
11097

111-
result
112-
.send(result_str)
113-
.map_err(|e| Box::new(RpcClientError::Send(format!("{:?}", e))).into())
98+
result.send(result_str).map_err(|e| Box::new(e).into())
11499
}
115100
}
116101

@@ -119,26 +104,24 @@ pub(crate) struct SubscriptionHandler {}
119104

120105
impl HandleMessage for SubscriptionHandler {
121106
type ThreadMessage = String;
122-
type Error = ws::Error;
123107
type Context = MessageContext<Self::ThreadMessage>;
124-
type Result = ();
125108

126-
fn handle_message(&self, context: &mut Self::Context) -> Result<Self::Result, Self::Error> {
109+
fn handle_message(&self, context: &mut Self::Context) -> WsResult<()> {
127110
let result = &context.result;
128111
let out = &context.out;
129112
let msg = &context.msg;
130113

131114
info!("got on_subscription_msg {}", msg);
132115
let value: serde_json::Value =
133-
serde_json::from_str(msg.as_text()?).map_err(|e| Box::new(RpcClientError::Serde(e)))?;
116+
serde_json::from_str(msg.as_text()?).map_err(|e| Box::new(e))?;
134117

135118
match value["id"].as_str() {
136119
Some(_idstr) => {
137120
warn!("Expected subscription, but received an id response instead: {:?}", value);
138121
},
139122
None => {
140-
let answer = serde_json::to_string(&value["params"]["result"])
141-
.map_err(|e| Box::new(RpcClientError::Serde(e)))?;
123+
let answer =
124+
serde_json::to_string(&value["params"]["result"]).map_err(|e| Box::new(e))?;
142125

143126
if let Err(e) = result.send(answer) {
144127
// This may happen if the receiver has unsubscribed.

0 commit comments

Comments
 (0)