Merge rust-bitcoin/rust-bitcoin#1314: Return custom error from `Network::from_str`

d1b7dff094 return custom error from `Network::from_str` (Noah)

Pull request description:

  Fix #1292

  Had some time so got this out of the way.

ACKs for top commit:
  apoelstra:
    ACK d1b7dff094
  tcharding:
    ACK d1b7dff094

Tree-SHA512: f6566f4df74c697cc3d84eca4e4c45bb5da9e86fe32e5f6e257a3e8c3e22fc375f5f307c7f96edd4536a80c1d1c13535f6073a1a093911468abb015040c2888b
This commit is contained in:
Andrew Poelstra 2022-10-18 19:30:42 +00:00
commit e10aa552f6
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 14 additions and 8 deletions

View File

@ -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<Self, Self::Err> {
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)
}