From 78dfca41e6ee891ca652922ae8d587fa62b88d38 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Sun, 12 Oct 2025 21:05:51 +0800 Subject: [PATCH] feat: add error handling for duplicated semantic ID and label name in database operations --- .../src/framework/db/label_db_service_impl.rs | 18 ++++++++++++++++-- .../src/framework/db/post_db_service_impl.rs | 18 ++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/backend/feature/post/src/framework/db/label_db_service_impl.rs b/backend/feature/post/src/framework/db/label_db_service_impl.rs index f189fd1..9a0d775 100644 --- a/backend/feature/post/src/framework/db/label_db_service_impl.rs +++ b/backend/feature/post/src/framework/db/label_db_service_impl.rs @@ -32,7 +32,14 @@ impl LabelDbService for LabelDbServiceImpl { ) .fetch_one(&self.db_pool) .await - .map_err(|e| PostError::Unexpected(DatabaseError(e).into()))?; + .map_err(|e| { + if let sqlx::Error::Database(db_err) = &e { + if db_err.constraint() == Some("idx_label_name") { + return PostError::DuplicatedLabelName; + } + } + PostError::Unexpected(DatabaseError(e).into()) + })?; Ok(id) } @@ -50,7 +57,14 @@ impl LabelDbService for LabelDbServiceImpl { ) .execute(&self.db_pool) .await - .map_err(|e| PostError::Unexpected(DatabaseError(e).into()))? + .map_err(|e| { + if let sqlx::Error::Database(db_err) = &e { + if db_err.constraint() == Some("idx_label_name") { + return PostError::DuplicatedLabelName; + } + } + PostError::Unexpected(DatabaseError(e).into()) + })? .rows_affected(); if affected_rows == 0 { diff --git a/backend/feature/post/src/framework/db/post_db_service_impl.rs b/backend/feature/post/src/framework/db/post_db_service_impl.rs index fa46e0e..ac68214 100644 --- a/backend/feature/post/src/framework/db/post_db_service_impl.rs +++ b/backend/feature/post/src/framework/db/post_db_service_impl.rs @@ -211,7 +211,14 @@ impl PostDbService for PostDbServiceImpl { ) .fetch_one(&mut *tx) .await - .map_err(|e| PostError::Unexpected(DatabaseError(e).into()))?; + .map_err(|e| { + if let sqlx::Error::Database(db_err) = &e { + if db_err.constraint() == Some("idx_post_semantic_id") { + return PostError::DuplicatedSemanticId; + } + } + PostError::Unexpected(DatabaseError(e).into()) + })?; for (order, &label_id) in label_ids.iter().enumerate() { sqlx::query!( @@ -266,7 +273,14 @@ impl PostDbService for PostDbServiceImpl { ) .execute(&mut *tx) .await - .map_err(|e| PostError::Unexpected(DatabaseError(e).into()))? + .map_err(|e| { + if let sqlx::Error::Database(db_err) = &e { + if db_err.constraint() == Some("idx_post_semantic_id") { + return PostError::DuplicatedSemanticId; + } + } + PostError::Unexpected(DatabaseError(e).into()) + })? .rows_affected(); if affected_rows == 0 {