use crate::OptionType;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum TransactionError {
#[error("{method} not implemented for {type_name}")]
NotImplemented {
method: &'static str,
type_name: &'static str,
},
#[error("unsupported option type in transaction: {option_type:?}")]
UnsupportedOptionType {
option_type: OptionType,
},
#[error("transaction error: {reason}")]
Other {
reason: String,
},
}
impl TransactionError {
#[cold]
#[inline(never)]
#[must_use]
pub fn not_implemented(method: &'static str, type_name: &'static str) -> Self {
TransactionError::NotImplemented { method, type_name }
}
#[cold]
#[inline(never)]
#[must_use]
pub fn unsupported_option_type(option_type: OptionType) -> Self {
TransactionError::UnsupportedOptionType { option_type }
}
#[cold]
#[inline(never)]
#[must_use]
pub fn other(reason: impl Into<String>) -> Self {
TransactionError::Other {
reason: reason.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_not_implemented_display() {
let err = TransactionError::not_implemented("add_transaction", "Position");
assert!(err.to_string().contains("add_transaction"));
assert!(err.to_string().contains("Position"));
}
#[test]
fn test_not_implemented_match_fields() {
let err = TransactionError::not_implemented("get_transactions", "Position");
match err {
TransactionError::NotImplemented { method, type_name } => {
assert_eq!(method, "get_transactions");
assert_eq!(type_name, "Position");
}
other => panic!("expected NotImplemented, got {other:?}"),
}
}
#[test]
fn test_unsupported_option_type_display() {
let err = TransactionError::unsupported_option_type(OptionType::American);
assert!(err.to_string().contains("American"));
}
#[test]
fn test_other_constructor_accepts_str_and_string() {
let from_str = TransactionError::other("boom");
let from_string = TransactionError::other(String::from("kaboom"));
assert!(matches!(from_str, TransactionError::Other { .. }));
assert!(matches!(from_string, TransactionError::Other { .. }));
assert!(from_str.to_string().contains("boom"));
assert!(from_string.to_string().contains("kaboom"));
}
}