From 0c988f70b0f155bca46969b30b2d47c990443a74 Mon Sep 17 00:00:00 2001 From: Raniro Coelho Date: Thu, 7 Aug 2025 21:30:21 -0300 Subject: [PATCH] Handle errors in text analysis endpoint --- README.md | 3 +-- api/app/api/endpoints/text_analysis.py | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bc7fa99..5141f50 100644 --- a/README.md +++ b/README.md @@ -48,8 +48,7 @@ docker-compose up -d [x] Database Connection and ORM Setup [x] Running with Uvicorn - -[] Text Analysis Endpoints +[x] Text Analysis Endpoints [] Testing the API diff --git a/api/app/api/endpoints/text_analysis.py b/api/app/api/endpoints/text_analysis.py index fdb92ef..7ffad60 100644 --- a/api/app/api/endpoints/text_analysis.py +++ b/api/app/api/endpoints/text_analysis.py @@ -1,6 +1,8 @@ """API endpoint for text analysis.""" -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session +from sqlalchemy.exc import SQLAlchemyError + from app.api.dependencies import get_db from app.schemas.text import TextAnalysisRequest, TextAnalysisResponse from app.services.text_analysis import analyze_text @@ -17,4 +19,12 @@ async def analyze(request: TextAnalysisRequest, db: Session = Depends(get_db)): Returns a detailed analysis of the text, including word analysis, phrase analysis, and overall AI likelihood. """ - return analyze_text(request.text, db) + if not request.text.strip(): + raise HTTPException(status_code=400, detail="Text must not be empty") + + try: + return analyze_text(request.text, db) + except SQLAlchemyError as exc: # pragma: no cover - defensive + raise HTTPException(status_code=500, detail="Database error") from exc + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc