Skip to main content

cala_ledger/transaction/
error.rs

1use thiserror::Error;
2
3use super::repo::{
4    TransactionColumn, TransactionCreateError, TransactionFindError, TransactionModifyError,
5    TransactionQueryError,
6};
7use cala_types::primitives::TransactionId;
8
9#[derive(Error, Debug)]
10pub enum TransactionError {
11    #[error("TransactionError - Sqlx: {0}")]
12    Sqlx(#[from] sqlx::Error),
13    #[error("TransactionError - Create: {0}")]
14    Create(TransactionCreateError),
15    #[error("TransactionError - Modify: {0}")]
16    Modify(#[from] TransactionModifyError),
17    #[error("TransactionError - Find: {0}")]
18    Find(TransactionFindError),
19    #[error("TransactionError - Query: {0}")]
20    Query(#[from] TransactionQueryError),
21    #[error("TransactionError - NotFound: id '{0}' not found")]
22    CouldNotFindById(TransactionId),
23    #[error("TransactionError - NotFound: external id '{0}' not found")]
24    CouldNotFindByExternalId(String),
25    #[error("TransactionError - DuplicateExternalId: external_id '{0}' already exists")]
26    DuplicateExternalId(String),
27    #[error("TransactionError - DuplicateId: id '{0}' already exists")]
28    DuplicateId(String),
29    #[error("TransactionError - AlreadyVoided: transaction '{0}' is already voided")]
30    AlreadyVoided(TransactionId),
31}
32
33impl TransactionError {
34    pub fn was_not_found(&self) -> bool {
35        matches!(
36            self,
37            Self::CouldNotFindById(_) | Self::CouldNotFindByExternalId(_)
38        )
39    }
40}
41
42impl From<TransactionFindError> for TransactionError {
43    fn from(error: TransactionFindError) -> Self {
44        match error {
45            TransactionFindError::NotFound {
46                column: Some(TransactionColumn::Id),
47                value,
48                ..
49            } => Self::CouldNotFindById(value.parse().expect("invalid uuid")),
50            TransactionFindError::NotFound {
51                column: Some(TransactionColumn::ExternalId),
52                value,
53                ..
54            } => Self::CouldNotFindByExternalId(value),
55            other => Self::Find(other),
56        }
57    }
58}
59
60impl From<TransactionCreateError> for TransactionError {
61    fn from(error: TransactionCreateError) -> Self {
62        match error {
63            TransactionCreateError::ConstraintViolation {
64                column: Some(TransactionColumn::ExternalId),
65                value,
66                ..
67            } => Self::DuplicateExternalId(value.unwrap_or_default()),
68            TransactionCreateError::ConstraintViolation {
69                column: Some(TransactionColumn::Id),
70                value,
71                ..
72            } => Self::DuplicateId(value.unwrap_or_default()),
73            other => Self::Create(other),
74        }
75    }
76}