Skip to content

Commit 1ebc919

Browse files
committed
refactor: cleanup usages of the anyhow! macro
- Remove redundant `.map_err(|err| anyhow!(err))` when used before a `with_context` as it does the error conversion. - Remove redundant `format!` in `anyhow!(format!(..))` as the anyhow macro already support formatting. - Prefer usage of `with_context` instead of `ok_or(anyhow!(..))` or `ok_or_else(|| anyhow!(..))` when working with options, so the error conversion is gracefully done by the anyhow crate instead of our code, and this often results in leaner code. - Simplify `anyhow::anyhow!(e).context(..)` to `e.context(..)` when the error is already an anyhow error. - When using the macro is unavoidable and it print the error in its message, add another context layer by wrapping the error first then adding the previous message as context. e.g: from `anyhow!("Error context: {e}")` to `anyhow!(e.to_string()).context("Error context")`. - Add a anyhow context to some errors. Note: Some macro usage are unavoidable, e.g when the inner error can't be implicitly converted to `anyhow::Error`.
1 parent 2cd85d6 commit 1ebc919

File tree

79 files changed

+362
-415
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+362
-415
lines changed

examples/client-cardano-database-v2/src/main.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,16 +75,20 @@ async fn main() -> MithrilResult<()> {
7575

7676
let latest_hash = cardano_database_snapshots
7777
.first()
78-
.ok_or(anyhow!(
79-
"No Cardano database snapshot could be listed from aggregator: '{}'",
80-
args.aggregator_endpoint
81-
))?
78+
.with_context(|| {
79+
format!(
80+
"No Cardano database snapshot could be listed from aggregator: '{}'",
81+
args.aggregator_endpoint
82+
)
83+
})?
8284
.hash
8385
.as_ref();
8486

85-
let cardano_database_snapshot = client.cardano_database_v2().get(latest_hash).await?.ok_or(
86-
anyhow!("A Cardano database should exist for hash '{latest_hash}'"),
87-
)?;
87+
let cardano_database_snapshot = client
88+
.cardano_database_v2()
89+
.get(latest_hash)
90+
.await?
91+
.with_context(|| format!("A Cardano database should exist for hash '{latest_hash}'"))?;
8892

8993
let unpacked_dir = work_dir.join("unpack");
9094
std::fs::create_dir(&unpacked_dir).unwrap();

examples/client-cardano-database/src/main.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,18 +74,20 @@ async fn main() -> MithrilResult<()> {
7474

7575
let last_digest = snapshots
7676
.first()
77-
.ok_or(anyhow!(
78-
"No snapshots could be listed from aggregator: '{}'",
79-
args.aggregator_endpoint
80-
))?
77+
.with_context(|| {
78+
format!(
79+
"No snapshots could be listed from aggregator: '{}'",
80+
args.aggregator_endpoint
81+
)
82+
})?
8183
.digest
8284
.as_ref();
8385

8486
let snapshot = client
8587
.cardano_database()
8688
.get(last_digest)
8789
.await?
88-
.ok_or(anyhow!("A snapshot should exist for hash '{last_digest}'"))?;
90+
.with_context(|| format!("A snapshot should exist for hash '{last_digest}'"))?;
8991

9092
let unpacked_dir = work_dir.join("unpack");
9193
std::fs::create_dir(&unpacked_dir).unwrap();

examples/client-cardano-stake-distribution/src/main.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//!
33
//! In this example, the client interacts by default with a real aggregator (`release-preprod`) to get the data.
44
5-
use anyhow::anyhow;
5+
use anyhow::Context;
66
use clap::Parser;
77
use slog::info;
88
use std::{str::FromStr, sync::Arc};
@@ -57,19 +57,21 @@ async fn main() -> MithrilResult<()> {
5757

5858
let last_epoch = cardano_stake_distributions
5959
.first()
60-
.ok_or(anyhow!(
61-
"No Cardano stake distributions could be listed from aggregator: '{}'",
62-
args.aggregator_endpoint
63-
))?
60+
.with_context(|| {
61+
format!(
62+
"No Cardano stake distributions could be listed from aggregator: '{}'",
63+
args.aggregator_endpoint
64+
)
65+
})?
6466
.epoch;
6567

6668
let cardano_stake_distribution = client
6769
.cardano_stake_distribution()
6870
.get_by_epoch(last_epoch)
6971
.await?
70-
.ok_or(anyhow!(
71-
"A Cardano stake distribution should exist for hash '{last_epoch}'"
72-
))?;
72+
.with_context(|| {
73+
format!("A Cardano stake distribution should exist for hash '{last_epoch}'")
74+
})?;
7375
info!(
7476
logger,
7577
"Fetched details of last Cardano stake distribution:\n{cardano_stake_distribution:#?}",

examples/client-mithril-stake-distribution/src/main.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//!
33
//! In this example, the client interacts by default with a real aggregator (`release-preprod`) to get the data.
44
5-
use anyhow::anyhow;
5+
use anyhow::Context;
66
use clap::Parser;
77
use slog::info;
88
use std::{str::FromStr, sync::Arc};
@@ -57,20 +57,22 @@ async fn main() -> MithrilResult<()> {
5757

5858
let last_hash = mithril_stake_distributions
5959
.first()
60-
.ok_or(anyhow!(
61-
"No Mithril stake distributions could be listed from aggregator: '{}'",
62-
args.aggregator_endpoint
63-
))?
60+
.with_context(|| {
61+
format!(
62+
"No Mithril stake distributions could be listed from aggregator: '{}'",
63+
args.aggregator_endpoint
64+
)
65+
})?
6466
.hash
6567
.as_ref();
6668

6769
let mithril_stake_distribution = client
6870
.mithril_stake_distribution()
6971
.get(last_hash)
7072
.await?
71-
.ok_or(anyhow!(
72-
"A Mithril stake distribution should exist for hash '{last_hash}'"
73-
))?;
73+
.with_context(|| {
74+
format!("A Mithril stake distribution should exist for hash '{last_hash}'")
75+
})?;
7476
info!(
7577
logger,
7678
"Fetched details of last Mithril stake distribution:\n{mithril_stake_distribution:#?}",

internal/cardano-node/mithril-cardano-node-chain/src/chain_observer/pallas_observer.rs

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ impl PallasChainObserver {
6666
async fn get_client(&self) -> StdResult<NodeClient> {
6767
self.new_client()
6868
.await
69-
.map_err(|err| anyhow!(err))
7069
.with_context(|| "PallasChainObserver failed to create new client")
7170
}
7271

@@ -75,12 +74,10 @@ impl PallasChainObserver {
7574
statequery
7675
.acquire(None)
7776
.await
78-
.map_err(|err| anyhow!(err))
7977
.with_context(|| "PallasChainObserver failed to acquire statequery")?;
8078

8179
let era = queries_v16::get_current_era(statequery)
8280
.await
83-
.map_err(|err| anyhow!(err))
8481
.with_context(|| "PallasChainObserver failed to get current era")?;
8582

8683
Ok(era)
@@ -91,17 +88,14 @@ impl PallasChainObserver {
9188
statequery
9289
.acquire(None)
9390
.await
94-
.map_err(|err| anyhow!(err))
9591
.with_context(|| "PallasChainObserver failed to acquire statequery")?;
9692

9793
let era = queries_v16::get_current_era(statequery)
9894
.await
99-
.map_err(|err| anyhow!(err))
10095
.with_context(|| "PallasChainObserver failed to get current era")?;
10196

10297
let epoch = queries_v16::get_block_epoch_number(statequery, era)
10398
.await
104-
.map_err(|err| anyhow!(err))
10599
.with_context(|| "PallasChainObserver failed to get block epoch number")?;
106100

107101
Ok(epoch)
@@ -129,7 +123,6 @@ impl PallasChainObserver {
129123
fn serialize_datum(&self, utxo: &PostAlonsoTransactionOutput) -> StdResult<TxDatum> {
130124
let datum = self.inspect_datum(utxo)?;
131125
let serialized = serde_json::to_string(&datum.to_json())
132-
.map_err(|err| anyhow!(err))
133126
.with_context(|| "PallasChainObserver failed to serialize datum")?;
134127

135128
Ok(TxDatum(serialized))
@@ -170,23 +163,19 @@ impl PallasChainObserver {
170163
statequery
171164
.acquire(None)
172165
.await
173-
.map_err(|err| anyhow!(err))
174166
.with_context(|| "PallasChainObserver failed to acquire statequery")?;
175167

176168
let era = queries_v16::get_current_era(statequery)
177169
.await
178-
.map_err(|err| anyhow!(err))
179170
.with_context(|| "PallasChainObserver failed to get current era")?;
180171

181172
let addr: Address = Address::from_bech32(address)
182-
.map_err(|err| anyhow!(err))
183173
.with_context(|| "PallasChainObserver failed to parse address")?;
184174

185175
let addr: Addr = addr.to_vec().into();
186176
let addrs: Addrs = vec![addr];
187177
let utxo = queries_v16::get_utxo_by_address(statequery, era, addrs)
188178
.await
189-
.map_err(|err| anyhow!(err))
190179
.with_context(|| "PallasChainObserver failed to get utxo")?;
191180

192181
Ok(utxo)
@@ -200,17 +189,14 @@ impl PallasChainObserver {
200189
statequery
201190
.acquire(None)
202191
.await
203-
.map_err(|err| anyhow!(err))
204192
.with_context(|| "PallasChainObserver failed to acquire statequery")?;
205193

206194
let era = queries_v16::get_current_era(statequery)
207195
.await
208-
.map_err(|err| anyhow!(err))
209196
.with_context(|| "PallasChainObserver failed to get current era")?;
210197

211198
let state_snapshot = queries_v16::get_stake_snapshots(statequery, era, BTreeSet::new())
212199
.await
213-
.map_err(|err| anyhow!(err))
214200
.with_context(|| "PallasChainObserver failed to get stake snapshot")?;
215201

216202
Ok(state_snapshot)
@@ -219,7 +205,6 @@ impl PallasChainObserver {
219205
/// Returns the stake pool hash from the given bytestring.
220206
fn get_stake_pool_hash(&self, key: &Bytes) -> Result<String, ChainObserverError> {
221207
let pool_id_bech32 = encode_bech32("pool", key)
222-
.map_err(|err| anyhow!(err))
223208
.with_context(|| "PallasChainObserver failed to encode stake pool hash")?;
224209
Ok(pool_id_bech32)
225210
}
@@ -282,15 +267,13 @@ impl PallasChainObserver {
282267

283268
let current_kes_period = chain_point.slot_or_default() / slots_per_kes_period;
284269
Ok(u32::try_from(current_kes_period)
285-
.map_err(|err| anyhow!(err))
286270
.with_context(|| "PallasChainObserver failed to convert kes period")?)
287271
}
288272

289273
/// Fetches the current chain point using the provided `statequery` client.
290274
async fn do_get_chain_point_state_query(&self, statequery: &mut Client) -> StdResult<Point> {
291275
let chain_point = queries_v16::get_chain_point(statequery)
292276
.await
293-
.map_err(|err| anyhow!(err))
294277
.with_context(|| "PallasChainObserver failed to get chain point")?;
295278

296279
Ok(chain_point)
@@ -300,7 +283,6 @@ impl PallasChainObserver {
300283
async fn do_get_chain_block_no(&self, statequery: &mut Client) -> StdResult<ChainBlockNumber> {
301284
let chain_block_number = queries_v16::get_chain_block_no(statequery)
302285
.await
303-
.map_err(|err| anyhow!(err))
304286
.with_context(|| "PallasChainObserver failed to get chain block number")?;
305287

306288
Ok(chain_block_number)
@@ -310,7 +292,6 @@ impl PallasChainObserver {
310292
async fn do_get_current_era_state_query(&self, statequery: &mut Client) -> StdResult<u16> {
311293
let era = queries_v16::get_current_era(statequery)
312294
.await
313-
.map_err(|err| anyhow!(err))
314295
.with_context(|| "PallasChainObserver failed to get current era")?;
315296

316297
Ok(era)
@@ -324,7 +305,6 @@ impl PallasChainObserver {
324305
let era = self.do_get_current_era_state_query(statequery).await?;
325306
let genesis_config = queries_v16::get_genesis_config(statequery, era)
326307
.await
327-
.map_err(|err| anyhow!(err))
328308
.with_context(|| "PallasChainObserver failed to get genesis config")?;
329309

330310
Ok(genesis_config)
@@ -335,7 +315,6 @@ impl PallasChainObserver {
335315
statequery
336316
.acquire(None)
337317
.await
338-
.map_err(|err| anyhow!(err))
339318
.with_context(|| "PallasChainObserver failed to acquire statequery")?;
340319

341320
let chain_point = self.do_get_chain_point_state_query(statequery).await?;
@@ -365,7 +344,6 @@ impl PallasChainObserver {
365344
statequery
366345
.acquire(None)
367346
.await
368-
.map_err(|err| anyhow!(err))
369347
.with_context(|| "PallasChainObserver failed to acquire statequery")?;
370348

371349
let chain_point = self.do_get_chain_point_state_query(statequery).await?;
@@ -389,13 +367,11 @@ impl PallasChainObserver {
389367
statequery
390368
.send_release()
391369
.await
392-
.map_err(|err| anyhow!(err))
393370
.with_context(|| "PallasChainObserver send release failed")?;
394371

395372
statequery
396373
.send_done()
397374
.await
398-
.map_err(|err| anyhow!(err))
399375
.with_context(|| "PallasChainObserver send done failed")?;
400376

401377
Ok(())
@@ -407,7 +383,6 @@ impl PallasChainObserver {
407383
.chainsync()
408384
.send_done()
409385
.await
410-
.map_err(|err| anyhow!(err))
411386
.with_context(|| "PallasChainObserver chainsync send done failed")?;
412387
Ok(())
413388
}

internal/cardano-node/mithril-cardano-node-chain/src/chain_reader/pallas_chain_reader.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::path::{Path, PathBuf};
22

3-
use anyhow::{Context, anyhow};
3+
use anyhow::Context;
44
use async_trait::async_trait;
55
use pallas_network::{
66
facades::NodeClient,
@@ -41,7 +41,6 @@ impl PallasChainReader {
4141
let magic = self.network.magic_id();
4242
NodeClient::connect(&self.socket, magic)
4343
.await
44-
.map_err(|err| anyhow!(err))
4544
.with_context(|| "PallasChainReader failed to create a new client")
4645
}
4746

internal/cardano-node/mithril-cardano-node-chain/src/entities/datum.rs

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use anyhow::{Context, anyhow};
1+
use anyhow::Context;
22
use pallas_codec::minicbor::{Decode, Decoder, decode};
33
use pallas_primitives::{ToCanonicalJson, alonzo::PlutusData};
44
use serde::{Deserialize, Serialize};
@@ -31,9 +31,7 @@ pub fn try_inspect<R>(inner: Vec<u8>) -> StdResult<R>
3131
where
3232
for<'b> R: Decode<'b, ()>,
3333
{
34-
decode(&inner)
35-
.map_err(|e| anyhow!(e))
36-
.with_context(|| format!("failed to decode datum: {}", hex::encode(&inner)))
34+
decode(&inner).with_context(|| format!("failed to decode datum: {}", hex::encode(&inner)))
3735
}
3836

3937
/// [Datums] represents a list of [TxDatum].
@@ -60,25 +58,24 @@ impl TxDatum {
6058
pub fn get_fields_by_type(&self, type_name: &TxDatumFieldTypeName) -> StdResult<Vec<Value>> {
6159
let tx_datum_raw = &self.0;
6260
// 1- Parse the Utxo raw data to a hashmap
63-
let v: HashMap<String, Value> = serde_json::from_str(tx_datum_raw).map_err(|e| {
64-
TxDatumError::InvalidContent(anyhow!(e).context("tx datum was = '{tx_datum_raw}'"))
65-
})?;
61+
let v: HashMap<String, Value> = serde_json::from_str(tx_datum_raw)
62+
.with_context(|| format!("tx datum was = '{tx_datum_raw}'"))
63+
.map_err(TxDatumError::InvalidContent)?;
64+
6665
// 2- Convert the 'fields' entry to a vec of json objects
67-
let fields = v.get("fields").ok_or_else(|| {
68-
TxDatumError::InvalidContent(
69-
anyhow!("Error: missing 'fields' entry, tx datum was = '{tx_datum_raw}'"),
70-
)
71-
})?.as_array().ok_or_else(|| {
72-
TxDatumError::InvalidContent(
73-
anyhow!("Error: 'fields' entry is not correctly structured, tx datum was = '{tx_datum_raw}'"),
74-
)
75-
})?;
66+
let fields = v.get("fields")
67+
.with_context(|| format!("Error: missing 'fields' entry, tx datum was = '{tx_datum_raw}'"))
68+
.map_err(TxDatumError::InvalidContent)?
69+
.as_array()
70+
.with_context(|| format!("Error: 'fields' entry is not correctly structured, tx datum was = '{tx_datum_raw}'"))
71+
.map_err(TxDatumError::InvalidContent)?;
72+
7673
// 3- Filter the vec (keep the ones that match the given type), and retrieve the nth entry of this filtered vec
7774
Ok(fields
7875
.iter()
7976
.filter(|&field| field.get(type_name.to_string()).is_some())
8077
.map(|field| field.get(type_name.to_string()).unwrap().to_owned())
81-
.collect::<_>())
78+
.collect())
8279
}
8380

8481
/// Retrieves the nth field of the datum with given type
@@ -90,9 +87,8 @@ impl TxDatum {
9087
Ok(self
9188
.get_fields_by_type(type_name)?
9289
.get(index)
93-
.ok_or_else(|| {
94-
TxDatumError::InvalidContent(anyhow!("Error: missing field at index {index}"))
95-
})?
90+
.with_context(|| format!("Error: missing field at index {index}"))
91+
.map_err(TxDatumError::InvalidContent)?
9692
.to_owned())
9793
}
9894
}

internal/cardano-node/mithril-cardano-node-internal-database/src/immutable_file_observer.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ impl ImmutableFileSystemObserver {
4848
impl ImmutableFileObserver for ImmutableFileSystemObserver {
4949
async fn get_last_immutable_number(&self) -> StdResult<u64> {
5050
let immutable_file_number = ImmutableFile::list_completed_in_dir(&self.db_path)
51-
.map_err(|e| anyhow!(e))
5251
.with_context(|| "Immutable File System Observer can not list all immutable files")?
5352
.into_iter()
5453
.next_back()

0 commit comments

Comments
 (0)