From ba80ace1be4cc2dc8d05f15bcfc0a42ceb4b32fd Mon Sep 17 00:00:00 2001 From: John O'Keefe Date: Mon, 26 Jan 2026 11:32:11 -0500 Subject: [PATCH] Enhance error handling in ebook handlers - Add pgx.ErrNoRows checks in GetEbook and GetReadingProgress - Improve error handling in GetEbookRating with proper status codes - Return consistent error responses across all endpoints - Add missing pgx import for proper error comparison --- internal/handlers/ebook.go | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/internal/handlers/ebook.go b/internal/handlers/ebook.go index 118959d..07044a4 100644 --- a/internal/handlers/ebook.go +++ b/internal/handlers/ebook.go @@ -10,6 +10,7 @@ import ( "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/labstack/echo/v4" ) @@ -107,6 +108,9 @@ func (h *Handler) GetEbook(c echo.Context) error { ebook, err := h.db.GetEbook(c.Request().Context(), pgtype.UUID{Bytes: id, Valid: true}) if err != nil { + if err == pgx.ErrNoRows { + return c.JSON(http.StatusNotFound, map[string]string{"error": "ebook not found"}) + } return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()}) } @@ -258,13 +262,16 @@ func (h *Handler) GetReadingProgress(c echo.Context) error { UserID: pgtype.UUID{Bytes: userUUID, Valid: true}, }) if err != nil { - // If no progress found, return default - return c.JSON(http.StatusOK, map[string]interface{}{ - "ebook_id": ebookIdStr, - "user_id": userID, - "current_page": 0, - "total_pages": nil, - }) + if err == pgx.ErrNoRows { + // If no progress found, return default + return c.JSON(http.StatusOK, map[string]interface{}{ + "ebook_id": ebookIdStr, + "user_id": userID, + "current_page": 0, + "total_pages": nil, + }) + } + return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()}) } return c.JSON(http.StatusOK, progress) @@ -338,8 +345,11 @@ func (h *Handler) GetEbookRating(c echo.Context) error { UserID: pgtype.UUID{Bytes: userUUID, Valid: true}, }) if err != nil { - // If no rating found, return 404 - return c.JSON(http.StatusNotFound, map[string]string{"error": "rating not found"}) + if err == pgx.ErrNoRows { + // If no rating found, return 404 + return c.JSON(http.StatusNotFound, map[string]string{"error": "rating not found"}) + } + return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()}) } return c.JSON(http.StatusOK, rating)