Skip to main content

mudra_cli/
error.rs

1//! Error types for the currency converter application
2
3use thiserror::Error;
4
5/// Custom error type for currency converter operations
6#[derive(Error, Debug)]
7pub enum CurrencyError {
8    /// Network-related errors (timeouts, connection failures)
9    #[error("Network error: {0}")]
10    Network(#[from] reqwest::Error),
11
12    /// JSON parsing errors
13    #[error("JSON parsing error: {0}")]
14    Json(#[from] serde_json::Error),
15
16    /// API-specific errors (invalid currency codes, rate limits)
17    #[error("API error: {message}")]
18    Api { message: String },
19
20    /// Invalid currency code
21    #[error("Invalid currency code: {code}")]
22    InvalidCurrency { code: String },
23
24    /// Invalid amount (negative, NaN, etc.)
25    #[error("Invalid amount: {amount}")]
26    InvalidAmount { amount: f64 },
27
28    /// Configuration errors (missing API key, invalid settings)
29    #[error("Configuration error: {message}")]
30    Configuration { message: String },
31
32    /// Generic conversion errors
33    #[error("Conversion error: {message}")]
34    Conversion { message: String },
35}
36
37impl CurrencyError {
38    /// Create a new API error
39    pub fn api<S: Into<String>>(message: S) -> Self {
40        CurrencyError::Api {
41            message: message.into(),
42        }
43    }
44
45    /// Create a new configuration error
46    pub fn configuration<S: Into<String>>(message: S) -> Self {
47        CurrencyError::Configuration {
48            message: message.into(),
49        }
50    }
51
52    /// Create a new conversion error
53    pub fn conversion<S: Into<String>>(message: S) -> Self {
54        CurrencyError::Conversion {
55            message: message.into(),
56        }
57    }
58
59    /// Create an invalid currency error
60    pub fn invalid_currency<S: Into<String>>(code: S) -> Self {
61        CurrencyError::InvalidCurrency { code: code.into() }
62    }
63
64    /// Create an invalid amount error
65    pub fn invalid_amount(amount: f64) -> Self {
66        CurrencyError::InvalidAmount { amount }
67    }
68}
69
70/// Type alias for Results using our custom error type
71/// This is a common Rust pattern - makes code cleaner
72pub type Result<T> = std::result::Result<T, CurrencyError>;