// SPDX-FileCopyrightText: 2024 Aravinth Manivannan // // SPDX-License-Identifier: AGPL-3.0-or-later use std::borrow::Cow; use cqrs_es::persist::PersistenceError; use sqlx::Error as SqlxError; use crate::inventory::application::port::output::db::errors::InventoryDBError; impl From for InventoryDBError { fn from(e: SqlxError) -> Self { log::error!("[postgres] err: {}", e); if let SqlxError::Database(err) = e { if err.code() == Some(Cow::from("23505")) { let msg = err.message(); if msg.contains("cqrs_inventory_store_query_store_id_key") { return Self::DuplicateStoreID; } else { println!("{msg}"); } } } Self::InternalError } } /// map custom row not found error to DB error pub fn map_row_not_found_err(e: SqlxError, row_not_found: InventoryDBError) -> InventoryDBError { if let SqlxError::RowNotFound = e { row_not_found } else { e.into() } } #[derive(Debug)] pub enum PostgresAggregateError { OptimisticLock, ConnectionError(Box), DeserializationError(Box), UnknownError(Box), } impl From for PostgresAggregateError { fn from(err: SqlxError) -> Self { // TODO: improve error handling match &err { SqlxError::Database(database_error) => { if let Some(code) = database_error.code() { if code.as_ref() == "23505" { return PostgresAggregateError::OptimisticLock; } } PostgresAggregateError::UnknownError(Box::new(err)) } SqlxError::Io(_) | SqlxError::Tls(_) => { PostgresAggregateError::ConnectionError(Box::new(err)) } _ => PostgresAggregateError::UnknownError(Box::new(err)), } } } impl From for PersistenceError { fn from(err: PostgresAggregateError) -> Self { match err { PostgresAggregateError::OptimisticLock => PersistenceError::OptimisticLockError, PostgresAggregateError::ConnectionError(error) => { PersistenceError::ConnectionError(error) } PostgresAggregateError::DeserializationError(error) => { PersistenceError::UnknownError(error) } PostgresAggregateError::UnknownError(error) => PersistenceError::UnknownError(error), } } }