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

21
Cargo.lock generated
View file

@ -296,6 +296,7 @@ dependencies = [
"fpdec",
"serde",
"serde_with",
"thiserror",
]
[[package]]
@ -395,6 +396,26 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f6586b7f764adc0231f4c79be7b920e766bb2f3e51b3661cdb263828f19994"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12bafc5b54507e0149cdf1b145a5d80ab80a90bcd9275df43d4fff68460f6c21"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "time"
version = "0.3.13"

View file

@ -10,3 +10,4 @@ csv = "1.1"
fpdec = "0.5"
serde = { version = "1.0", features = ["derive"] }
serde_with = "2.0"
thiserror = "1.0"

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)
}