Skip to content

Commit

Permalink
Use anyhow to add context to error messages (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
casey authored Mar 19, 2022
1 parent 74b58ad commit 5e064f2
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 32 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ edition = "2021"
autotests = false

[dependencies]
anyhow = "1.0.56"
bitcoin = "0.27.1"
bitcoincore-rpc = "0.14.0"
chrono = "0.4.19"
Expand Down
2 changes: 1 addition & 1 deletion src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl FromStr for Bytes {
"tib" => TI,
"pib" => PI,
"eib" => EI,
_ => return Err("invalid suffix".into()),
_ => return Err(anyhow!("invalid suffix")),
};

Ok(Bytes((value * multiple as f64) as usize))
Expand Down
31 changes: 17 additions & 14 deletions src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,18 @@ impl Index {
options
.rpc_url
.as_ref()
.ok_or("This command requires `--rpc-url`")?,
.ok_or_else(|| anyhow!("This command requires `--rpc-url`"))?,
options
.cookie_file
.as_ref()
.map(|path| Auth::CookieFile(path.clone()))
.unwrap_or(Auth::None),
)?;
)
.context("Failed to connect to RPC URL")?;

Ok(Self {
client,
database: Database::open(options)?,
database: Database::open(options).context("Failed to open database")?,
sleep_until: Cell::new(Instant::now()),
})
}
Expand All @@ -45,17 +46,19 @@ impl Index {
}

fn client(&self) -> &Client {
let now = Instant::now();
if cfg!(target_os = "macos") {
let now = Instant::now();

let sleep_until = self.sleep_until.get();
let sleep_until = self.sleep_until.get();

if sleep_until > now {
std::thread::sleep(sleep_until - now);
}
if sleep_until > now {
std::thread::sleep(sleep_until - now);
}

self
.sleep_until
.set(Instant::now() + Duration::from_millis(2));
self
.sleep_until
.set(Instant::now() + Duration::from_millis(2));
}

&self.client
}
Expand Down Expand Up @@ -108,7 +111,7 @@ impl Index {
let prev_hash = wtx.blockhash_at_height(prev_height)?.unwrap();

if prev_hash != block.header.prev_blockhash.as_ref() {
return Err("Reorg detected at or before {prev_height}".into());
return Err(anyhow!("Reorg detected at or before {prev_height}"));
}
}

Expand Down Expand Up @@ -138,7 +141,7 @@ impl Index {

let ordinal_ranges = wtx
.get_ordinal_ranges(key.as_slice())?
.ok_or("Could not find outpoint in index")?;
.ok_or_else(|| anyhow!("Could not find outpoint in index"))?;

let new = input_ordinal_ranges.len();

Expand Down Expand Up @@ -224,7 +227,7 @@ impl Index {
while remaining > 0 {
let range = input_ordinal_ranges
.pop_front()
.ok_or("Insufficient inputs for transaction outputs")?;
.ok_or_else(|| anyhow!("Insufficient inputs for transaction outputs"))?;

let count = range.1 - range.0;

Expand Down
2 changes: 1 addition & 1 deletion src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl Key {

pub(crate) fn decode(buffer: &[u8]) -> Result<Self> {
if buffer.len() != 24 {
return Err("Buffer too small to decode key from".into());
return Err(anyhow!("Buffer too small to decode key from"));
}

Ok(Key {
Expand Down
22 changes: 11 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use {
arguments::Arguments, bytes::Bytes, epoch::Epoch, height::Height, index::Index, key::Key,
options::Options, ordinal::Ordinal, sat_point::SatPoint, subcommand::Subcommand,
},
anyhow::{anyhow, Context, Error},
bitcoin::{
blockdata::constants::COIN_VALUE, consensus::Decodable, consensus::Encodable, Block, BlockHash,
OutPoint, Transaction, Txid,
Expand All @@ -29,28 +30,27 @@ use {
},
};

#[cfg(feature = "redb")]
use redb_database::{Database, WriteTransaction};

#[cfg(not(feature = "redb"))]
use lmdb_database::{Database, WriteTransaction};

mod arguments;
mod bytes;
mod epoch;
mod height;
mod index;
mod key;
#[cfg(not(feature = "redb"))]
mod lmdb_database;
mod options;
mod ordinal;
mod sat_point;
mod subcommand;

#[cfg(feature = "redb")]
mod redb_database;
#[cfg(feature = "redb")]
use redb_database::{Database, WriteTransaction};

#[cfg(not(feature = "redb"))]
mod lmdb_database;
#[cfg(not(feature = "redb"))]
use lmdb_database::{Database, WriteTransaction};
mod sat_point;
mod subcommand;

type Error = Box<dyn std::error::Error + Send + Sync>;
type Result<T = (), E = Error> = std::result::Result<T, E>;

static INTERRUPTS: AtomicU64 = AtomicU64::new(0);
Expand Down
2 changes: 1 addition & 1 deletion src/subcommand/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Find {
}
Ok(())
}
None => Err("Ordinal has not been mined as of index height".into()),
None => Err(anyhow!("Ordinal has not been mined as of index height")),
}
}
}
2 changes: 1 addition & 1 deletion src/subcommand/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl List {
}
Ok(())
}
None => Err("Output not found".into()),
None => Err(anyhow!("Output not found")),
}
}
}
4 changes: 2 additions & 2 deletions src/subcommand/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub(crate) struct Name {
impl Name {
pub(crate) fn run(self) -> Result {
if self.name.is_empty() || self.name.chars().any(|c| !('a'..='z').contains(&c)) {
return Err("Invalid name".into());
return Err(anyhow!("Invalid name"));
}

let mut min = 0;
Expand All @@ -32,7 +32,7 @@ impl Name {
}

if max - min == 0 {
return Err("Name out of range".into());
return Err(anyhow!("Name out of range"));
}

guess = min + (max - min) / 2;
Expand Down
2 changes: 1 addition & 1 deletion src/subcommand/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub(crate) struct Traits {
impl Traits {
pub(crate) fn run(self) -> Result {
if self.ordinal > Ordinal::LAST {
return Err("Invalid ordinal".into());
return Err(anyhow!("Invalid ordinal"));
}

let n = self.ordinal.n();
Expand Down

0 comments on commit 5e064f2

Please sign in to comment.