Skip to content

Commit

Permalink
refactor: clean up error definitions
Browse files Browse the repository at this point in the history
  • Loading branch information
cgorenflo committed Sep 1, 2023
1 parent a1bb261 commit 0b6d5b3
Show file tree
Hide file tree
Showing 17 changed files with 91 additions and 87 deletions.
23 changes: 13 additions & 10 deletions ampd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::pin::Pin;
use cosmos_sdk_proto::cosmos::{
auth::v1beta1::query_client::QueryClient, tx::v1beta1::service_client::ServiceClient,
};
use error_stack::{FutureExt, Report, Result, ResultExt};
use error_stack::{FutureExt, Result, ResultExt};
use tokio::signal::unix::{signal, SignalKind};
use tokio::task::JoinSet;
use tokio_stream::Stream;
Expand Down Expand Up @@ -52,20 +52,20 @@ pub async fn run(cfg: Config, state_path: PathBuf) -> Result<(), Error> {
multisig,
} = cfg;

let tm_client =
tendermint_rpc::HttpClient::new(tm_jsonrpc.to_string().as_str()).map_err(Error::new)?;
let tm_client = tendermint_rpc::HttpClient::new(tm_jsonrpc.to_string().as_str())
.change_context(Error::Connection)?;
let service_client = ServiceClient::connect(tm_grpc.to_string())
.await
.map_err(Error::new)?;
.change_context(Error::Connection)?;
let query_client = QueryClient::connect(tm_grpc.to_string())
.await
.map_err(Error::new)?;
.change_context(Error::Connection)?;
let multisig_client = MultisigClient::connect(tofnd_config.party_uid, tofnd_config.url)
.await
.map_err(Error::new)?;
.change_context(Error::Tofnd)?;
let ecdsa_client = SharableEcdsaClient::new(multisig_client);

let mut state_updater = StateUpdater::new(state_path).map_err(Error::new)?;
let mut state_updater = StateUpdater::new(state_path).change_context(Error::StateUpdater)?;
let pub_key = match state_updater.state().pub_key {
Some(pub_key) => pub_key,
None => {
Expand All @@ -83,7 +83,9 @@ pub async fn run(cfg: Config, state_path: PathBuf) -> Result<(), Error> {
.account_id(PREFIX)
.expect("failed to convert to account identifier")
.into();
let account = account(query_client, &worker).await.map_err(Error::new)?;
let account = account(query_client, &worker)
.await
.change_context(Error::Broadcaster)?;

let broadcaster = broadcaster::BroadcastClientBuilder::default()
.client(service_client)
Expand Down Expand Up @@ -176,7 +178,8 @@ where
worker.clone(),
config.voting_verifier,
config.name,
evm::json_rpc::Client::new_http(&config.rpc_url).map_err(Error::new)?,
evm::json_rpc::Client::new_http(&config.rpc_url)
.change_context(Error::Connection)?,
self.broadcaster.client(),
);

Expand Down Expand Up @@ -258,7 +261,7 @@ where
let res = match (set.join_next().await, token.is_cancelled()) {
(Some(result), false) => {
token.cancel();
result.map_err(Error::new).map_err(Report::from)?
result.change_context(Error::Threading)?
}
(Some(_), true) => Ok(()),
(None, _) => panic!("all tasks exited unexpectedly"),
Expand Down
18 changes: 6 additions & 12 deletions ampd/src/report.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::backtrace::Backtrace;
use std::collections::VecDeque;
use std::iter::FromIterator;
use std::panic::Location;
use std::{backtrace::Backtrace, fmt::Display};

use error_stack::{AttachmentKind, Context, Frame, FrameKind, Report};
use thiserror::Error;
use tracing::error;
use valuable::Valuable;

#[derive(Error, Debug)]
Expand All @@ -19,17 +20,10 @@ pub enum Error {
StateUpdater,
#[error("tofnd failed")]
Tofnd,
#[error("{0}")]
Error(String),
}

impl Error {
pub fn new<T>(msg: T) -> Error
where
T: Display,
{
Error::Error(msg.to_string())
}
#[error("connection failed")]
Connection,
#[error("thread execution failed")]
Threading,
}

#[derive(Valuable, PartialEq, Debug, Default)]
Expand Down
2 changes: 1 addition & 1 deletion ampd/src/tofnd/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub enum Error {
KeygenFailed,
#[error("sign failed")]
SignFailed,
#[error("{0}")]
#[error(transparent)]
FromHex(#[from] hex::FromHexError),
#[error("parsing failed")]
ParsingFailed,
Expand Down
21 changes: 14 additions & 7 deletions ampd/tests/report.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
use error_stack::Report;
use thiserror::Error;

use ampd::report::{Error, LoggableError};
use ampd::report::LoggableError;

#[derive(Error, Debug)]
enum Error {
#[error("{0}")]
FromString(String),
}

// Do not move this test or the location field checks break
#[test]
fn correct_error_log() {
let report = Report::new(Error::new("error1".to_string()))
let report = Report::new(Error::FromString("error1".to_string()))
.attach_printable("foo1")
.change_context(Error::new("error2".to_string()))
.change_context(Error::FromString("error2".to_string()))
.attach_printable("test1")
.attach_printable("test2")
.change_context(Error::new("error3".to_string()))
.change_context(Error::FromString("error3".to_string()))
.attach(5);

let mut err = LoggableError::from(&report);
Expand All @@ -25,15 +32,15 @@ fn correct_error_log() {
let expected_err = LoggableError {
msg: "error3".to_string(),
attachments: vec!["opaque attachment".to_string()],
location: "ampd/tests/report.rs:13:10".to_string(),
location: "ampd/tests/report.rs:20:10".to_string(),
cause: Some(Box::new(LoggableError {
msg: "error2".to_string(),
attachments: vec!["test1".to_string(), "test2".to_string()],
location: "ampd/tests/report.rs:10:10".to_string(),
location: "ampd/tests/report.rs:17:10".to_string(),
cause: Some(Box::new(LoggableError {
msg: "error1".to_string(),
attachments: vec!["foo1".to_string()],
location: "ampd/tests/report.rs:8:18".to_string(),
location: "ampd/tests/report.rs:15:18".to_string(),
cause: None,
backtrace: None,
})),
Expand Down
4 changes: 2 additions & 2 deletions contracts/aggregate-verifier/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ use thiserror::Error;

#[derive(Error, Debug, PartialEq)]
pub enum ContractError {
#[error("{0}")]
#[error(transparent)]
Std(#[from] StdError),

#[error("{0}")]
#[error(transparent)]
RouterError(#[from] connection_router::ContractError),

#[error("received invalid verifier reply: {0}")]
Expand Down
2 changes: 1 addition & 1 deletion contracts/batching/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ use thiserror::Error;

#[derive(Error, Debug)]
pub enum ContractError {
#[error("{0}")]
#[error(transparent)]
Std(#[from] StdError),
}
18 changes: 9 additions & 9 deletions contracts/connection-router/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,29 @@ use crate::types::ChainName;

#[derive(Error, Debug, PartialEq)]
pub enum ContractError {
#[error("{0}")]
#[error(transparent)]
Std(#[from] StdError),

#[error("caller is not authorized")]
Unauthorized {},
Unauthorized,

#[error("chain already exists")]
ChainAlreadyExists {},
ChainAlreadyExists,

#[error("chain name is invalid")]
InvalidChainName {},
InvalidChainName,

#[error("message ID is invalid")]
InvalidMessageID {},
InvalidMessageID,

#[error("chain is not found")]
ChainNotFound {},
ChainNotFound,

#[error("gateway is not registered")]
GatewayNotRegistered {},
GatewayNotRegistered,

#[error("gateway is already registered")]
GatewayAlreadyRegistered {},
GatewayAlreadyRegistered,

#[error("chain is frozen")]
ChainFrozen { chain: ChainName },
Expand All @@ -36,7 +36,7 @@ pub enum ContractError {
InvalidAddress(String),

#[error("source chain does not match registered gateway")]
WrongSourceChain {},
WrongSourceChain,
}

impl From<ContractError> for StdError {
Expand Down
38 changes: 19 additions & 19 deletions contracts/connection-router/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ fn route_non_existing_chain() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::ChainNotFound {}, res.downcast().unwrap());
assert_eq!(ContractError::ChainNotFound , res.downcast().unwrap());
}

#[test]
Expand Down Expand Up @@ -188,7 +188,7 @@ fn message_id() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::InvalidMessageID {}, res.downcast().unwrap());
assert_eq!(ContractError::InvalidMessageID , res.downcast().unwrap());

// don't prepend source chain
let bad_id = msg.id.split(&msg.source_chain).collect::<Vec<&str>>()[0];
Expand All @@ -204,7 +204,7 @@ fn message_id() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::InvalidMessageID {}, res.downcast().unwrap());
assert_eq!(ContractError::InvalidMessageID , res.downcast().unwrap());

let res = config
.app
Expand All @@ -218,7 +218,7 @@ fn message_id() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::InvalidMessageID {}, res.downcast().unwrap());
assert_eq!(ContractError::InvalidMessageID , res.downcast().unwrap());

let res = config
.app
Expand All @@ -232,7 +232,7 @@ fn message_id() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::InvalidMessageID {}, res.downcast().unwrap());
assert_eq!(ContractError::InvalidMessageID , res.downcast().unwrap());
}

#[test]
Expand Down Expand Up @@ -301,7 +301,7 @@ fn wrong_source_chain() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::WrongSourceChain {}, res.downcast().unwrap());
assert_eq!(ContractError::WrongSourceChain , res.downcast().unwrap());
}

#[test]
Expand Down Expand Up @@ -379,7 +379,7 @@ fn authorization() {
)
.unwrap_err();

assert_eq!(ContractError::Unauthorized {}, res.downcast().unwrap());
assert_eq!(ContractError::Unauthorized , res.downcast().unwrap());

let res = config.app.execute_contract(
config.admin_address.clone(),
Expand All @@ -405,7 +405,7 @@ fn authorization() {
)
.unwrap_err();

assert_eq!(ContractError::Unauthorized {}, res.downcast().unwrap());
assert_eq!(ContractError::Unauthorized , res.downcast().unwrap());

let res = config.app.execute_contract(
config.admin_address.clone(),
Expand All @@ -431,7 +431,7 @@ fn authorization() {
)
.unwrap_err();

assert_eq!(ContractError::Unauthorized {}, res.downcast().unwrap());
assert_eq!(ContractError::Unauthorized , res.downcast().unwrap());

let res = config
.app
Expand All @@ -446,7 +446,7 @@ fn authorization() {
)
.unwrap_err();

assert_eq!(ContractError::Unauthorized {}, res.downcast().unwrap());
assert_eq!(ContractError::Unauthorized, res.downcast().unwrap());

let res = config.app.execute_contract(
config.admin_address.clone(),
Expand Down Expand Up @@ -536,7 +536,7 @@ fn upgrade_gateway_incoming() {
)
.unwrap_err();
assert_eq!(
ContractError::GatewayNotRegistered {},
ContractError::GatewayNotRegistered ,
res.downcast().unwrap()
);

Expand Down Expand Up @@ -569,7 +569,7 @@ fn register_chain_test() {
)
.unwrap_err();
assert_eq!(
ContractError::GatewayNotRegistered {},
ContractError::GatewayNotRegistered ,
res.downcast().unwrap()
);

Expand All @@ -583,7 +583,7 @@ fn register_chain_test() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::ChainNotFound {}, res.downcast().unwrap());
assert_eq!(ContractError::ChainNotFound , res.downcast().unwrap());

register_chain(&mut config, &polygon);
let res = config.app.execute_contract(
Expand Down Expand Up @@ -614,7 +614,7 @@ fn chain_already_registered() {
)
.unwrap_err();
assert_eq!(
ContractError::ChainAlreadyExists {},
ContractError::ChainAlreadyExists ,
res.downcast().unwrap()
);

Expand All @@ -632,7 +632,7 @@ fn chain_already_registered() {
)
.unwrap_err();
assert_eq!(
ContractError::ChainAlreadyExists {},
ContractError::ChainAlreadyExists ,
res.downcast().unwrap()
);
}
Expand All @@ -652,7 +652,7 @@ fn invalid_chain_name() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::InvalidChainName {}, res.downcast().unwrap());
assert_eq!(ContractError::InvalidChainName , res.downcast().unwrap());

let res = config
.app
Expand All @@ -666,7 +666,7 @@ fn invalid_chain_name() {
&[],
)
.unwrap_err();
assert_eq!(ContractError::InvalidChainName {}, res.downcast().unwrap());
assert_eq!(ContractError::InvalidChainName , res.downcast().unwrap());
}

#[test]
Expand All @@ -688,7 +688,7 @@ fn gateway_already_registered() {
)
.unwrap_err();
assert_eq!(
ContractError::GatewayAlreadyRegistered {},
ContractError::GatewayAlreadyRegistered ,
res.downcast().unwrap()
);

Expand All @@ -706,7 +706,7 @@ fn gateway_already_registered() {
)
.unwrap_err();
assert_eq!(
ContractError::GatewayAlreadyRegistered {},
ContractError::GatewayAlreadyRegistered ,
res.downcast().unwrap()
);
}
Expand Down
Loading

0 comments on commit 0b6d5b3

Please sign in to comment.