Skip to content

Commit

Permalink
blockbook: make proper use of thiserror functionalities
Browse files Browse the repository at this point in the history
This commit uses the `#[from]` attribute to:

- delegate the `source()` implementation of the `std::error::Error`
trait to the source error (could possibly also be done using the
`#[source]` attribute).

- generate `From` trait implementations.

Note: The `#[from]` attribute always implies that the corresponding
field is also the source, so no need to specify the `#[source]`
attribute. See:
https://docs.rs/thiserror/1.0.47/thiserror/index.html
  • Loading branch information
bachmannscode committed Aug 23, 2023
1 parent ffb22eb commit e3461d1
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 17 deletions.
16 changes: 2 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,26 +75,14 @@ pub mod websocket;
pub enum Error {
/// An error during a network request.
#[error("error occured during the network request: {0}")]
RequestError(reqwest::Error),
RequestError(#[from] reqwest::Error),
/// An error while parsing a URL.
#[error("invalid url: {0}")]
UrlError(url::ParseError),
UrlError(#[from] url::ParseError),
}

type Result<T> = std::result::Result<T, Error>;

impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Self::RequestError(e)
}
}

impl From<url::ParseError> for Error {
fn from(e: url::ParseError) -> Self {
Self::UrlError(e)
}
}

/// A REST client that can query a Blockbook server.
///
/// Provides a set methods that allow strongly typed
Expand Down
6 changes: 3 additions & 3 deletions src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ pub enum Error {
WebsocketClosed,
/// A WebSocket error.
#[error("the websocket connection experienced a fatal error: {0:?}\nreinstantiate the client to reconnect")]
Websocket(std::sync::Arc<tokio_tungstenite::tungstenite::Error>),
Websocket(#[from] std::sync::Arc<tokio_tungstenite::tungstenite::Error>),
}

type Result<T> = std::result::Result<T, Error>;
Expand Down Expand Up @@ -198,7 +198,7 @@ impl Client {
pub async fn new(url: url::Url) -> Result<Self> {
let stream = tokio_tungstenite::connect_async(url)
.await
.map_err(|e| Error::Websocket(e.into()))?;
.map_err(std::sync::Arc::new)?;
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let (job_tx, job_rx) = futures::channel::mpsc::channel(10);
tokio::spawn(Self::process(stream.0, job_rx, shutdown_rx));
Expand Down Expand Up @@ -282,7 +282,7 @@ impl Client {
response_channels
.iter_mut()
.map(|(_,ch)| {
ch.send(Err(Error::Websocket(err.clone())))
ch.send(Err(err.clone().into()))
})
.collect::<futures::stream::FuturesUnordered<_>>()
.collect::<Vec<std::result::Result<_, _>>>()
Expand Down

0 comments on commit e3461d1

Please # to comment.