transaction: use proper 'ParseError' type

This commit is contained in:
Bruno BELANYI 2022-08-23 12:26:53 +02:00
parent 19b5f3390d
commit ab8ecf8121
5 changed files with 44 additions and 6 deletions

11
src/error.rs Normal file
View file

@ -0,0 +1,11 @@
//! Error types for this crate.
use thiserror::Error;
/// Any kind of error that can happen when deserializing a [crate::Transaction] value.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Error)]
pub enum ParseError {
#[error("amount not provided")]
MissingAmount,
#[error("unknown transaction type '{0}'")]
UnknownTx(String),
}

View file

@ -1,5 +1,8 @@
pub mod core;
pub use crate::core::*;
pub mod error;
pub use crate::error::*;
pub mod transaction;
pub use crate::transaction::*;

View file

@ -1,5 +1,8 @@
//! Define all supported transactions.
use crate::core::{ClientId, TxAmount, TxId};
use crate::{
core::{ClientId, TxAmount, TxId},
ParseError,
};
use serde::Deserialize;
@ -40,8 +43,7 @@ struct TransactionRecord<'a> {
}
impl TryFrom<TransactionRecord<'_>> for Transaction {
// FIXME: use an actual error type.
type Error = String;
type Error = ParseError;
fn try_from(value: TransactionRecord<'_>) -> Result<Self, Self::Error> {
let TransactionRecord {
@ -53,17 +55,17 @@ impl TryFrom<TransactionRecord<'_>> for Transaction {
let transaction = match type_ {
"deposit" => {
let amount = amount.ok_or("Missing amount for transaction")?;
let amount = amount.ok_or(ParseError::MissingAmount)?;
Transaction::Deposit(Deposit { client, tx, amount })
}
"withdrawal" => {
let amount = amount.ok_or("Missing amount for transaction")?;
let amount = amount.ok_or(ParseError::MissingAmount)?;
Transaction::Withdrawal(Withdrawal { client, tx, amount })
}
"dispute" => Transaction::Dispute(Dispute { client, tx }),
"resolve" => Transaction::Resolve(Resolve { client, tx }),
"chargeback" => Transaction::Chargeback(Chargeback { client, tx }),
_ => return Err(format!("Unkown transaction type '{}'", type_)),
_ => return Err(ParseError::UnknownTx(type_.into())),
};
Ok(transaction)
}