From c931100c48f9e93a0ec1fe516d21b040979792e0 Mon Sep 17 00:00:00 2001 From: yyasha Date: Mon, 29 Jan 2024 15:32:35 +0300 Subject: [PATCH] error handling for category not found --- .../handlers/recipesByCategory/recipesByCategory.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/internal/http-server/handlers/recipesByCategory/recipesByCategory.go b/internal/http-server/handlers/recipesByCategory/recipesByCategory.go index 6401ebe..d473c62 100644 --- a/internal/http-server/handlers/recipesByCategory/recipesByCategory.go +++ b/internal/http-server/handlers/recipesByCategory/recipesByCategory.go @@ -2,11 +2,13 @@ package recipes_by_category import ( "context" + "errors" "log/slog" "net/http" "recipes/internal/domain/models" resp "recipes/internal/lib/api/response" "recipes/internal/lib/logger/sl" + "recipes/internal/storage" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/render" @@ -28,7 +30,7 @@ type RecipesProvider interface { GetRecipesByCategory(ctx context.Context, offset, limit int, category string) ([]models.Recipe, error) } -const getRecipesLimit int = 16 +const GetRecipesLimit int = 16 func New(log *slog.Logger, recipesProvider RecipesProvider) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -57,8 +59,13 @@ func New(log *slog.Logger, recipesProvider RecipesProvider) http.HandlerFunc { return } // get recipes from storage - recipes, err := recipesProvider.GetRecipesByCategory(r.Context(), getRecipesLimit*(int(req.Page)-1), getRecipesLimit, req.Category) + recipes, err := recipesProvider.GetRecipesByCategory(r.Context(), GetRecipesLimit*(int(req.Page)-1), GetRecipesLimit, req.Category) if err != nil { + if errors.Is(err, storage.ErrCategoryNotFound) { + log.Error("failed to get recipes by category from storage", sl.Err(err)) + render.JSON(w, r, resp.Error("category not found")) + return + } log.Error("failed to get recipes from storage", sl.Err(err)) render.JSON(w, r, resp.Error("failed to get recipes")) return