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
+19 -9
View File
@@ -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)