From d1b7dff09409f80b8b5fc08b2acb3e4bdf6373ff Mon Sep 17 00:00:00 2001 From: Noah <34389972+nlanson@users.noreply.github.com> Date: Mon, 10 Oct 2022 19:37:14 +1100 Subject: [PATCH] return custom error from `Network::from_str` --- bitcoin/src/network/constants.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/bitcoin/src/network/constants.rs b/bitcoin/src/network/constants.rs index 614b642a..4a0ce10c 100644 --- a/bitcoin/src/network/constants.rs +++ b/bitcoin/src/network/constants.rs @@ -106,8 +106,20 @@ impl Network { } } +/// An error in parsing network string. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParseNetworkError(String); + +impl fmt::Display for ParseNetworkError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write_err!(f, "failed to parse {} as network", self.0; self) + } +} +impl_std_error!(ParseNetworkError); + impl FromStr for Network { - type Err = io::Error; + type Err = ParseNetworkError; + #[inline] fn from_str(s: &str) -> Result { use Network::*; @@ -117,13 +129,7 @@ impl FromStr for Network { "testnet" => Testnet, "signet" => Signet, "regtest" => Regtest, - _ => { - #[cfg(feature = "std")] - let message = format!("Unknown network (type {})", s); - #[cfg(not(feature = "std"))] - let message = "Unknown network"; - return Err(io::Error::new(io::ErrorKind::InvalidInput, message)); - } + _ => return Err(ParseNetworkError(s.to_owned())) }; Ok(network) }