1use std::{error, fmt};
2
3#[derive(Debug, PartialEq, Clone)]
5pub enum MoneyError {
6 InvalidCurrency,
7 InvalidAmount,
8 InvalidRatio,
9 CurrencyMismatch {
11 expected: &'static str,
12 actual: &'static str,
13 },
14 DivisionByZero,
16 Overflow,
18 PrecisionLoss,
20}
21
22impl fmt::Display for MoneyError {
23 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24 match self {
25 MoneyError::InvalidCurrency => write!(f, "Currency was not valid"),
26 MoneyError::InvalidAmount => write!(f, "Amount not parsable"),
27 MoneyError::InvalidRatio => write!(f, "Ratio was not valid"),
28 MoneyError::CurrencyMismatch { expected, actual } => {
29 write!(
30 f,
31 "Currency mismatch: expected {}, got {}",
32 expected, actual
33 )
34 }
35 MoneyError::DivisionByZero => write!(f, "Division by zero"),
36 MoneyError::Overflow => write!(f, "Arithmetic overflow"),
37 MoneyError::PrecisionLoss => write!(f, "Conversion would lose precision"),
38 }
39 }
40}
41
42impl error::Error for MoneyError {
43 fn description(&self) -> &str {
44 match self {
45 MoneyError::InvalidCurrency => "Currency was not valid",
46 MoneyError::InvalidAmount => "Amount not parsable",
47 MoneyError::InvalidRatio => "Ratio was not valid",
48 MoneyError::CurrencyMismatch { .. } => "Currency mismatch",
49 MoneyError::DivisionByZero => "Division by zero",
50 MoneyError::Overflow => "Arithmetic overflow",
51 MoneyError::PrecisionLoss => "Conversion would lose precision",
52 }
53 }
54}
55
56impl From<std::num::ParseIntError> for MoneyError {
57 fn from(_err: std::num::ParseIntError) -> MoneyError {
58 MoneyError::InvalidAmount
59 }
60}