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
This commit is contained in:
2026-01-26 11:32:11 -05:00
parent 6b4e5f0198
commit ba80ace1be
+10
View File
@@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"github.com/labstack/echo/v4" "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}) ebook, err := h.db.GetEbook(c.Request().Context(), pgtype.UUID{Bytes: id, Valid: true})
if err != nil { 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()}) return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
} }
@@ -258,6 +262,7 @@ func (h *Handler) GetReadingProgress(c echo.Context) error {
UserID: pgtype.UUID{Bytes: userUUID, Valid: true}, UserID: pgtype.UUID{Bytes: userUUID, Valid: true},
}) })
if err != nil { if err != nil {
if err == pgx.ErrNoRows {
// If no progress found, return default // If no progress found, return default
return c.JSON(http.StatusOK, map[string]interface{}{ return c.JSON(http.StatusOK, map[string]interface{}{
"ebook_id": ebookIdStr, "ebook_id": ebookIdStr,
@@ -266,6 +271,8 @@ func (h *Handler) GetReadingProgress(c echo.Context) error {
"total_pages": nil, "total_pages": nil,
}) })
} }
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
return c.JSON(http.StatusOK, progress) return c.JSON(http.StatusOK, progress)
} }
@@ -338,9 +345,12 @@ func (h *Handler) GetEbookRating(c echo.Context) error {
UserID: pgtype.UUID{Bytes: userUUID, Valid: true}, UserID: pgtype.UUID{Bytes: userUUID, Valid: true},
}) })
if err != nil { if err != nil {
if err == pgx.ErrNoRows {
// If no rating found, return 404 // If no rating found, return 404
return c.JSON(http.StatusNotFound, map[string]string{"error": "rating not found"}) 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) return c.JSON(http.StatusOK, rating)
} }