refactor(core): 1062 唯一键冲突判定收口至 core/db_errors

六个 service 各自复制的 _is_duplicate_entry(口径已漂移:rating/product
用 _ERR_DUP_ENTRY 常量、其余四处写字面量 1062)收敛为共享函数;
is_duplicate_entry 语义与文案注释各处保留,非 1062 完整性错误仍原样
上抛由全局处理器收敛。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
liuwenxinandClaude Code committed 2026-10-14 15:17:00 +08:00
1 parent 5a3778a424
commit a0086554b1
7 files changed
+31 -19

No files matched your search

+2 -5
View File
@@ -31,6 +31,7 @@ from app.core.constants import (
ACTION_UPDATE,
MODULE_RATING,
)
from app.core.db_errors import is_duplicate_entry
from app.core.exceptions import BadRequestError, NotFoundError
from app.models import CustomerRatingGrade, User
from app.repositories import rating_repository
@@ -44,9 +45,6 @@ logger = logging.getLogger(__name__)
_SCORE_FLOOR = Decimal("0")
_SCORE_CEIL = Decimal("100")
# 唯一键冲突的 MySQL 错误码(pymysql 原始异常 args 首位)
_ERR_DUP_ENTRY = 1062
def _to_out(grade: CustomerRatingGrade) -> RatingGradeOut:
"""ORM 对象转响应模型。分值 Decimal → str(分值红线出参口径)。"""
@@ -110,8 +108,7 @@ def _is_duplicate_entry(exc: IntegrityError) -> bool:
只有 1062 是「已存在」语义,可转业务提示;其余完整性错误(外键、
数据溢出等)语义未知,必须原样上抛交由全局处理器记 500,不能吞成 400。
"""
orig_args = getattr(exc.orig, "args", ())
return bool(orig_args) and orig_args[0] == _ERR_DUP_ENTRY
return is_duplicate_entry(exc)
def _raise_if_duplicate(exc: IntegrityError) -> None: