Skip to content

Commit

Permalink
add custom errors for state with recoverability tag
Browse files Browse the repository at this point in the history
  • Loading branch information
willyrgf committed Oct 11, 2023
1 parent 3f69b3d commit 9cea0ac
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
9 changes: 9 additions & 0 deletions mfm_machine/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 mfm_machine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.75"
52 changes: 52 additions & 0 deletions mfm_machine/src/state/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

#[derive(Debug)]
enum States<T: StateHandler> {
Setup(T),
Expand All @@ -8,6 +10,50 @@ trait StateHandler {
fn handler(&self);
}

#[derive(Debug)]
enum StateErrorRecoverability {
Recoverable,
Unrecoverable,
}

#[derive(Debug)]
enum StateError {
Unknown(StateErrorRecoverability),
RpcConnection(StateErrorRecoverability),
StorageAccess(StateErrorRecoverability),
OnChainError(StateErrorRecoverability),
OffChainError(StateErrorRecoverability),
ParsingInput(StateErrorRecoverability),
}

impl StateError {
pub fn is_recoverable(&self) -> bool {
match self {
Self::Unknown(recov) => matches!(recov, StateErrorRecoverability::Recoverable),
Self::RpcConnection(recov) => matches!(recov, StateErrorRecoverability::Recoverable),
Self::StorageAccess(recov) => matches!(recov, StateErrorRecoverability::Recoverable),
Self::OnChainError(recov) => matches!(recov, StateErrorRecoverability::Recoverable),
Self::OffChainError(recov) => matches!(recov, StateErrorRecoverability::Recoverable),
Self::ParsingInput(recov) => matches!(recov, StateErrorRecoverability::Recoverable),
}
}
}

impl fmt::Display for StateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unknown(_) => write!(f, "unknown error"),
Self::RpcConnection(_) => write!(f, "RPC connection error"),
Self::StorageAccess(_) => write!(f, "storage access error"),
Self::OnChainError(_) => write!(f, "on-chain error"),
Self::OffChainError(_) => write!(f, "off-chain error"),
Self::ParsingInput(_) => write!(f, "parsing input error"),
}
}
}

impl std::error::Error for StateError {}

struct SetupState;
impl StateHandler for SetupState {
fn handler(&self) {
Expand All @@ -34,4 +80,10 @@ mod test {
_ => panic!("expected Setup state"),
}
}

#[test]
fn custom_error_to_anyhow_error() {
let f = |error: StateError| -> anyhow::Error { error.into() };
f(StateError::Unknown(StateErrorRecoverability::Unrecoverable));
}
}

0 comments on commit 9cea0ac

Please sign in to comment.