Skip to main content

bitcoind_client/
error.rs

1//! [`Error`]
2
3use alloc::boxed::Box;
4
5use jsonrpc::serde_json;
6
7/// Error
8#[derive(Debug)]
9pub enum Error {
10    /// Bitcoin hex parsing error
11    #[cfg(feature = "simple-http")]
12    DecodeHex(corepc_types::bitcoin::hex::HexToArrayError),
13    /// mismatched IDs
14    IdMismatch,
15    /// Invalid cookie file
16    InvalidCookieFile,
17    /// `std::io`
18    #[cfg(feature = "std")]
19    Io(std::io::Error),
20    /// `jsonrpc`
21    JsonRpc(jsonrpc::Error),
22    /// error modeling a `corepc` type
23    #[cfg(feature = "simple-http")]
24    Model(Box<dyn core::error::Error + Send + Sync + 'static>),
25    /// parse integer
26    #[cfg(feature = "simple-http")]
27    ParseInt(core::num::ParseIntError),
28    /// Error returned in the response
29    Response(alloc::string::String),
30    /// `serde_json`
31    SerdeJson(serde_json::Error),
32}
33
34impl core::fmt::Display for Error {
35    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        match self {
37            #[cfg(feature = "simple-http")]
38            Self::DecodeHex(e) => write!(f, "{e}"),
39            Self::IdMismatch => write!(f, "request id mismatch"),
40            Self::InvalidCookieFile => write!(f, "invaild cookie file"),
41            #[cfg(feature = "std")]
42            Self::Io(e) => write!(f, "{e}"),
43            #[cfg(feature = "simple-http")]
44            Self::Model(e) => write!(f, "{e}"),
45            #[cfg(feature = "simple-http")]
46            Self::ParseInt(e) => write!(f, "{e}"),
47            Self::JsonRpc(e) => write!(f, "{e}"),
48            Self::SerdeJson(e) => write!(f, "{e}"),
49            Self::Response(s) => write!(f, "{s}"),
50        }
51    }
52}
53
54impl core::error::Error for Error {}
55
56impl Error {
57    /// Convert `e` to a [`Error::Model`] error.
58    #[cfg(feature = "simple-http")]
59    pub(crate) fn model<E>(e: E) -> Self
60    where
61        E: core::error::Error + Send + Sync + 'static,
62    {
63        Self::Model(Box::new(e))
64    }
65
66    /// Convert `e` to a [`jsonrpc::Error::Transport`] error.
67    pub(crate) fn transport<E>(e: E) -> Self
68    where
69        E: core::error::Error + Send + Sync + 'static,
70    {
71        Self::JsonRpc(jsonrpc::Error::Transport(Box::new(e)))
72    }
73}
74
75macro_rules! impl_error_from {
76    ( $to:ident, $from:ty ) => {
77        impl From<$from> for Error {
78            fn from(e: $from) -> Self {
79                Self::$to(e)
80            }
81        }
82    };
83}
84
85#[cfg(feature = "simple-http")]
86impl_error_from!(DecodeHex, corepc_types::bitcoin::hex::HexToArrayError);
87#[cfg(feature = "std")]
88impl_error_from!(Io, std::io::Error);
89impl_error_from!(JsonRpc, jsonrpc::Error);
90#[cfg(feature = "simple-http")]
91impl_error_from!(ParseInt, core::num::ParseIntError);
92impl_error_from!(SerdeJson, serde_json::Error);