Added errors for services

This commit is contained in:
KamilM1205 2025-09-23 22:03:00 +04:00
parent ab4b53fd40
commit c3c3d65d32
12 changed files with 217 additions and 86 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -194,6 +194,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Delete post summary: Delete post
tags: tags:
- post - post
@ -218,6 +226,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Get post by id summary: Get post by id
tags: tags:
- post - post
@ -246,6 +262,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Update post content summary: Update post content
tags: tags:
- post - post
@ -271,6 +295,10 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Get posts after offset summary: Get posts after offset
tags: tags:
- post - post
@ -290,6 +318,10 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Get all users summary: Get all users
tags: tags:
- user - user
@ -315,6 +347,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"409":
description: Conflict
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Create new user summary: Create new user
tags: tags:
- user - user
@ -336,6 +376,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Delete user summary: Delete user
tags: tags:
- user - user
@ -360,6 +408,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Find user by id summary: Find user by id
tags: tags:
- user - user
@ -390,6 +446,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Change user summary: Change user
tags: tags:
- user - user
@ -415,6 +479,14 @@ paths:
description: Bad Request description: Bad Request
schema: schema:
$ref: '#/definitions/responses.ErrorResponse' $ref: '#/definitions/responses.ErrorResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/responses.ErrorResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/responses.ErrorResponse'
summary: Find user by username summary: Find user by username
tags: tags:
- user - user

View file

@ -0,0 +1,15 @@
package errors
type AlreadyExistsError struct {
msg string
}
func NewAlreadyExistsError(msg string) *AlreadyExistsError {
return &AlreadyExistsError{
msg: msg,
}
}
func (e *AlreadyExistsError) Error() string {
return "Already exists: " + e.msg
}

View file

@ -4,12 +4,12 @@ type DBError struct {
msg string msg string
} }
func NewDBError(msg string) DBError { func NewDBError(msg string) *DBError {
return DBError{ return &DBError{
msg: msg, msg: msg,
} }
} }
func (e *DBError) Error() string { func (e *DBError) Error() string {
return e.msg return "Database error:" + e.msg
} }

View file

@ -11,5 +11,5 @@ func NewNotFoundError(msg string) *NotFoundError {
} }
func (e *NotFoundError) Error() string { func (e *NotFoundError) Error() string {
return e.msg return "Not found error: " + e.msg
} }

View file

@ -0,0 +1,15 @@
package errors
type ValidationError struct {
msg string
}
func NewValidationError(msg string) *ValidationError {
return &ValidationError{
msg: msg,
}
}
func (e *ValidationError) Error() string {
return "Validation error: " + e.msg
}

View file

@ -3,13 +3,11 @@ package services
import ( import (
"58team_blog/internal/application/commands" "58team_blog/internal/application/commands"
"58team_blog/internal/application/common" "58team_blog/internal/application/common"
ie "58team_blog/internal/application/errors" "58team_blog/internal/application/errors"
"58team_blog/internal/application/mapper" "58team_blog/internal/application/mapper"
"58team_blog/internal/application/queries" "58team_blog/internal/application/queries"
"58team_blog/internal/domain/entities" "58team_blog/internal/domain/entities"
"58team_blog/internal/domain/repository" "58team_blog/internal/domain/repository"
"errors"
"fmt"
"time" "time"
) )
@ -26,12 +24,12 @@ func CreatePostService(repo repository.PostRepository) PostService {
func (s *PostService) Create(cmd commands.CreatePostCommand) (*common.PostResult, error) { func (s *PostService) Create(cmd commands.CreatePostCommand) (*common.PostResult, error) {
entity, err := entities.CreatePost(cmd.UserId, cmd.Title, cmd.Description, cmd.Content) entity, err := entities.CreatePost(cmd.UserId, cmd.Title, cmd.Description, cmd.Content)
if err != nil { if err != nil {
return nil, err return nil, errors.NewValidationError("Invalid input data " + err.Error())
} }
post, err := s.repo.Create(&entity) post, err := s.repo.Create(&entity)
if err != nil { if err != nil {
return nil, fmt.Errorf("Db error: %s", err) return nil, errors.NewDBError(err.Error())
} }
result := mapper.CreatePostResultFromEntity(post) result := mapper.CreatePostResultFromEntity(post)
@ -42,15 +40,15 @@ func (s *PostService) Create(cmd commands.CreatePostCommand) (*common.PostResult
func (s *PostService) FindById(query queries.PostFindByIdQuery) (*queries.PostFindByIdResult, error) { func (s *PostService) FindById(query queries.PostFindByIdQuery) (*queries.PostFindByIdResult, error) {
post, err := s.repo.FindById(query.Id) post, err := s.repo.FindById(query.Id)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
if post == nil { if post == nil {
return nil, ie.NewNotFoundError("Post") return nil, errors.NewNotFoundError("Post")
} }
if err := post.Validate(); err != nil { if err := post.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
result := mapper.CreatePostFindByIdResultFromEntity(*post) result := mapper.CreatePostFindByIdResultFromEntity(*post)
@ -61,12 +59,12 @@ func (s *PostService) FindById(query queries.PostFindByIdQuery) (*queries.PostFi
func (s *PostService) FindAllByUserName(query queries.PostFindAllByUserNameQuery) (*queries.PostFindAllByUserNameResult, error) { func (s *PostService) FindAllByUserName(query queries.PostFindAllByUserNameQuery) (*queries.PostFindAllByUserNameResult, error) {
posts, err := s.repo.FindAllByUserName(query.UserName) posts, err := s.repo.FindAllByUserName(query.UserName)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
for _, p := range posts { for _, p := range posts {
if err := p.Validate(); err != nil { if err := p.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
} }
@ -78,12 +76,12 @@ func (s *PostService) FindAllByUserName(query queries.PostFindAllByUserNameQuery
func (s *PostService) GetAll() (*queries.PostGetAllResult, error) { func (s *PostService) GetAll() (*queries.PostGetAllResult, error) {
posts, err := s.repo.GetAll() posts, err := s.repo.GetAll()
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
for _, p := range posts { for _, p := range posts {
if err := p.Validate(); err != nil { if err := p.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
} }
@ -94,13 +92,12 @@ func (s *PostService) GetAll() (*queries.PostGetAllResult, error) {
func (s *PostService) GetAllOffset(offset int) (*queries.PostGetAllResult, error) { func (s *PostService) GetAllOffset(offset int) (*queries.PostGetAllResult, error) {
if offset < 0 { if offset < 0 {
return nil, errors.New("offset is less than 0") return nil, errors.NewValidationError("offset is less than 0")
} }
posts, err := s.repo.GetAllOffset(offset) posts, err := s.repo.GetAllOffset(offset)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
result := mapper.CreatePostGetAllResult(posts) result := mapper.CreatePostGetAllResult(posts)
@ -111,11 +108,11 @@ func (s *PostService) GetAllOffset(offset int) (*queries.PostGetAllResult, error
func (s *PostService) Update(cmd commands.UpdatePostCommand) (*common.PostResult, error) { func (s *PostService) Update(cmd commands.UpdatePostCommand) (*common.PostResult, error) {
post, err := s.repo.FindById(cmd.Id) post, err := s.repo.FindById(cmd.Id)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
if err := post.Validate(); err != nil { if err := post.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
post.Title = cmd.Title post.Title = cmd.Title
@ -124,7 +121,7 @@ func (s *PostService) Update(cmd commands.UpdatePostCommand) (*common.PostResult
post.UpdatedAt = time.Now() post.UpdatedAt = time.Now()
if err := post.Validate(); err != nil { if err := post.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
result := mapper.CreatePostResultFromEntity(post) result := mapper.CreatePostResultFromEntity(post)
@ -135,16 +132,16 @@ func (s *PostService) Update(cmd commands.UpdatePostCommand) (*common.PostResult
func (s *PostService) Delete(cmd commands.DeletePostCommand) error { func (s *PostService) Delete(cmd commands.DeletePostCommand) error {
post, err := s.repo.FindById(cmd.Id) post, err := s.repo.FindById(cmd.Id)
if err != nil { if err != nil {
return err return errors.NewDBError(err.Error())
} }
if err := post.Validate(); err != nil { if err := post.Validate(); err != nil {
return err return errors.NewValidationError(err.Error())
} }
err = s.repo.Delete(cmd.Id) err = s.repo.Delete(cmd.Id)
if err != nil { if err != nil {
return err return errors.NewDBError(err.Error())
} }
return nil return nil

View file

@ -3,12 +3,11 @@ package services
import ( import (
"58team_blog/internal/application/commands" "58team_blog/internal/application/commands"
"58team_blog/internal/application/common" "58team_blog/internal/application/common"
"58team_blog/internal/application/errors"
"58team_blog/internal/application/mapper" "58team_blog/internal/application/mapper"
"58team_blog/internal/application/queries" "58team_blog/internal/application/queries"
"58team_blog/internal/domain/entities" "58team_blog/internal/domain/entities"
"58team_blog/internal/domain/repository" "58team_blog/internal/domain/repository"
"errors"
"fmt"
) )
type UserService struct { type UserService struct {
@ -26,27 +25,23 @@ func (s *UserService) Create(cmd commands.CreateUserCommand) (*common.UserResult
{ {
user, err := s.repo.FindByName(cmd.Username) user, err := s.repo.FindByName(cmd.Username)
if err != nil { if err != nil {
return nil, fmt.Errorf("User.create findByName error: %s", err) return nil, errors.NewDBError(err.Error())
} }
if user != nil { if user != nil {
return nil, fmt.Errorf("User: %s already exists", user.UserName) return nil, errors.NewAlreadyExistsError("user: " + cmd.Username)
} }
} }
// Create new user // Create new user
user, err := entities.CreateUser(cmd.Username, cmd.Password) user, err := entities.CreateUser(cmd.Username, cmd.Password)
if err != nil { if err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
}
if err := user.Validate(); err != nil {
return nil, err
} }
entity, err := s.repo.Create(&user) entity, err := s.repo.Create(&user)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
result := mapper.CreateUserResultFromEntity(entity) result := mapper.CreateUserResultFromEntity(entity)
@ -57,11 +52,11 @@ func (s *UserService) Create(cmd commands.CreateUserCommand) (*common.UserResult
func (s *UserService) FindById(query queries.UserFindByIdQuery) (*queries.UserFindByIdResult, error) { func (s *UserService) FindById(query queries.UserFindByIdQuery) (*queries.UserFindByIdResult, error) {
entity, err := s.repo.FindById(query.Id) entity, err := s.repo.FindById(query.Id)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
if err := entity.Validate(); err != nil { if err := entity.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
result := mapper.CreateUserFindByIdResultFromEntity(entity) result := mapper.CreateUserFindByIdResultFromEntity(entity)
@ -72,11 +67,11 @@ func (s *UserService) FindById(query queries.UserFindByIdQuery) (*queries.UserFi
func (s *UserService) FindByName(query queries.UserFindByNameQuery) (*queries.UserFindByNameResult, error) { func (s *UserService) FindByName(query queries.UserFindByNameQuery) (*queries.UserFindByNameResult, error) {
entity, err := s.repo.FindByName(query.Name) entity, err := s.repo.FindByName(query.Name)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
if err := entity.Validate(); err != nil { if err := entity.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
result := mapper.CreateUserFindByNameResultFromEntity(entity) result := mapper.CreateUserFindByNameResultFromEntity(entity)
@ -86,12 +81,12 @@ func (s *UserService) FindByName(query queries.UserFindByNameQuery) (*queries.Us
func (s *UserService) GetAll() (*queries.UserGetAllResult, error) { func (s *UserService) GetAll() (*queries.UserGetAllResult, error) {
entityList, err := s.repo.GetAll() entityList, err := s.repo.GetAll()
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
for _, e := range entityList { for _, e := range entityList {
if err := e.Validate(); err != nil { if err := e.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
} }
@ -102,25 +97,25 @@ func (s *UserService) GetAll() (*queries.UserGetAllResult, error) {
func (s *UserService) Update(cmd commands.UpdateUserCommand) (*common.UserResult, error) { func (s *UserService) Update(cmd commands.UpdateUserCommand) (*common.UserResult, error) {
entity, err := s.repo.FindById(cmd.Id) entity, err := s.repo.FindById(cmd.Id)
if err != nil { if err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
if err := entity.Validate(); err != nil { if err := entity.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
if cmd.Username != entity.UserName { if cmd.Username != entity.UserName {
return nil, errors.New("You cannot change user name") return nil, errors.NewValidationError("You cannot change user name")
} }
entity.Password = cmd.Password entity.Password = cmd.Password
if err := entity.Validate(); err != nil { if err := entity.Validate(); err != nil {
return nil, err return nil, errors.NewValidationError(err.Error())
} }
if err := s.repo.Update(entity); err != nil { if err := s.repo.Update(entity); err != nil {
return nil, err return nil, errors.NewDBError(err.Error())
} }
result := mapper.CreateUserResultFromEntity(entity) result := mapper.CreateUserResultFromEntity(entity)
@ -130,15 +125,15 @@ func (s *UserService) Update(cmd commands.UpdateUserCommand) (*common.UserResult
func (s *UserService) Delete(cmd commands.DeleteUserCommand) error { func (s *UserService) Delete(cmd commands.DeleteUserCommand) error {
entity, err := s.repo.FindById(cmd.Id) entity, err := s.repo.FindById(cmd.Id)
if err != nil { if err != nil {
return err return errors.NewDBError(err.Error())
} }
if err := entity.Validate(); err != nil { if err := entity.Validate(); err != nil {
return err return errors.NewValidationError(err.Error())
} }
if err := s.repo.Delete(entity.Id); err != nil { if err := s.repo.Delete(entity.Id); err != nil {
return err return errors.NewDBError(err.Error())
} }
return nil return nil

View file

@ -7,6 +7,7 @@ import (
"58team_blog/internal/interfaces/api/mapper" "58team_blog/internal/interfaces/api/mapper"
"58team_blog/internal/interfaces/api/requests" "58team_blog/internal/interfaces/api/requests"
"58team_blog/internal/interfaces/api/responses" "58team_blog/internal/interfaces/api/responses"
"58team_blog/internal/utils"
"log" "log"
"net/http" "net/http"
"strconv" "strconv"
@ -42,7 +43,7 @@ func (r *PostController) Post(c *gin.Context) {
if err := c.BindJSON(&request); err != nil { if err := c.BindJSON(&request); err != nil {
log.Println(err) log.Println(err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "BadRequest") resp := responses.CreateErrorResponse(http.StatusBadRequest, err.Error())
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -64,8 +65,7 @@ func (r *PostController) Post(c *gin.Context) {
res, err := r.service.Create(cmd) res, err := r.service.Create(cmd)
if err != nil { if err != nil {
log.Println(err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusInternalServerError, "Internal server error")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -87,8 +87,7 @@ func (r *PostController) Post(c *gin.Context) {
func (r *PostController) GetAll(c *gin.Context) { func (r *PostController) GetAll(c *gin.Context) {
result, err := r.service.GetAll() result, err := r.service.GetAll()
if err != nil { if err != nil {
log.Println(err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusInternalServerError, "Internal server error")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -107,21 +106,21 @@ func (r *PostController) GetAll(c *gin.Context) {
// @Produce json // @Produce json
// @Success 200 {array} responses.GetListPostResponseItem // @Success 200 {array} responses.GetListPostResponseItem
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /post/offset/{offset} [get] // @Router /post/offset/{offset} [get]
func (r *PostController) GetAllWithOffset(c *gin.Context) { func (r *PostController) GetAllWithOffset(c *gin.Context) {
offset_param := c.Param("offset") offset_param := c.Param("offset")
offset, err := strconv.Atoi(offset_param) offset, err := strconv.Atoi(offset_param)
if err != nil { if err != nil {
log.Println("Post get all with offset error: ", err) log.Println("Post get all with offset error: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, "Invalid offset value")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
result, err := r.service.GetAllOffset(offset) result, err := r.service.GetAllOffset(offset)
if err != nil { if err != nil {
log.Println("Post get all with offset error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -140,6 +139,8 @@ func (r *PostController) GetAllWithOffset(c *gin.Context) {
// @Produce json // @Produce json
// @Success 200 {array} responses.PostResponse // @Success 200 {array} responses.PostResponse
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /post/{id} [get] // @Router /post/{id} [get]
func (r *PostController) GetById(c *gin.Context) { func (r *PostController) GetById(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
@ -158,8 +159,7 @@ func (r *PostController) GetById(c *gin.Context) {
posts, err := r.service.FindById(query) posts, err := r.service.FindById(query)
if err != nil { if err != nil {
log.Println("Post service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -181,6 +181,8 @@ func (r *PostController) GetById(c *gin.Context) {
// @Produce json // @Produce json
// @Success 200 {object} responses.PostResponse // @Success 200 {object} responses.PostResponse
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /post/{id} [put] // @Router /post/{id} [put]
func (r *PostController) Put(c *gin.Context) { func (r *PostController) Put(c *gin.Context) {
var request requests.PutPostRequest var request requests.PutPostRequest
@ -189,14 +191,14 @@ func (r *PostController) Put(c *gin.Context) {
id_valid, err := uuid.Parse(id) id_valid, err := uuid.Parse(id)
if err != nil { if err != nil {
log.Println("Post: invalid post id: ", err) log.Println("Post: invalid post id: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, err.Error())
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
if err := c.BindJSON(request); err != nil { if err := c.BindJSON(request); err != nil {
log.Println("Post request error: ", err) log.Println("Post request error: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, err.Error())
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -210,8 +212,7 @@ func (r *PostController) Put(c *gin.Context) {
post, err := r.service.Update(cmd) post, err := r.service.Update(cmd)
if err != nil { if err != nil {
log.Println("Post service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -229,13 +230,15 @@ func (r *PostController) Put(c *gin.Context) {
// @Produce json // @Produce json
// @Success 200 // @Success 200
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /post/{id} [delete] // @Router /post/{id} [delete]
func (r *PostController) Delete(c *gin.Context) { func (r *PostController) Delete(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
id_valid, err := uuid.Parse(id) id_valid, err := uuid.Parse(id)
if err != nil { if err != nil {
log.Println("Post: invalid post id: ", err) log.Println("Post: invalid post id: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, err.Error())
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -245,8 +248,7 @@ func (r *PostController) Delete(c *gin.Context) {
} }
err = r.service.Delete(cmd) err = r.service.Delete(cmd)
if err != nil { if err != nil {
log.Println("Post delete error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }

View file

@ -33,19 +33,21 @@ func CreateUserController(service *services.UserService) UserController {
// @Param request body requests.CreateUserRequest true "User data" // @Param request body requests.CreateUserRequest true "User data"
// @Success 201 {object} responses.UserResponse // @Success 201 {object} responses.UserResponse
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 409 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /user/ [post] // @Router /user/ [post]
func (r *UserController) Post(c *gin.Context) { func (r *UserController) Post(c *gin.Context) {
var request requests.CreateUserRequest var request requests.CreateUserRequest
if err := c.BindJSON(&request); err != nil { if err := c.BindJSON(&request); err != nil {
log.Println("User invalid request: ", err) log.Println("User invalid request: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, err.Error())
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
encrypted_password, err := utils.EncryptPassword(request.Password) encrypted_password, err := utils.EncryptPassword(request.Password)
if err != nil { if err != nil {
log.Println("User encrupt password error: ", err) log.Println("User encrypt password error: ", err)
resp := responses.CreateErrorResponse(http.StatusInternalServerError, "Internal server error") resp := responses.CreateErrorResponse(http.StatusInternalServerError, "Internal server error")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
@ -58,8 +60,7 @@ func (r *UserController) Post(c *gin.Context) {
user, err := r.service.Create(cmd) user, err := r.service.Create(cmd)
if err != nil { if err != nil {
log.Println("User service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -77,6 +78,8 @@ func (r *UserController) Post(c *gin.Context) {
// @Param id path string true "user id" // @Param id path string true "user id"
// @Success 200 {object} responses.UserResponse // @Success 200 {object} responses.UserResponse
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /user/{id} [get] // @Router /user/{id} [get]
func (r *UserController) FindById(c *gin.Context) { func (r *UserController) FindById(c *gin.Context) {
id_path := c.Param("id") id_path := c.Param("id")
@ -84,7 +87,7 @@ func (r *UserController) FindById(c *gin.Context) {
id, err := uuid.Parse(id_path) id, err := uuid.Parse(id_path)
if err != nil { if err != nil {
log.Println("User id error: ", err) log.Println("User id error: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, "Invalid user id")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -95,8 +98,7 @@ func (r *UserController) FindById(c *gin.Context) {
user, err := r.service.FindById(query) user, err := r.service.FindById(query)
if err != nil { if err != nil {
log.Println("User service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusNotFound, "Not found")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -113,6 +115,8 @@ func (r *UserController) FindById(c *gin.Context) {
// @Param name path string true "User name" // @Param name path string true "User name"
// @Success 200 {object} responses.UserResponse // @Success 200 {object} responses.UserResponse
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /user/name/{name} [get] // @Router /user/name/{name} [get]
func (r *UserController) FindByName(c *gin.Context) { func (r *UserController) FindByName(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
@ -123,8 +127,7 @@ func (r *UserController) FindByName(c *gin.Context) {
user, err := r.service.FindByName(query) user, err := r.service.FindByName(query)
if err != nil { if err != nil {
log.Println("User service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusNotFound, "Not found")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -139,12 +142,12 @@ func (r *UserController) FindByName(c *gin.Context) {
// @Produce json // @Produce json
// @Success 200 {object} responses.UserResponseList // @Success 200 {object} responses.UserResponseList
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /user/ [get] // @Router /user/ [get]
func (r *UserController) GetAll(c *gin.Context) { func (r *UserController) GetAll(c *gin.Context) {
users, err := r.service.GetAll() users, err := r.service.GetAll()
if err != nil { if err != nil {
log.Println("User service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusInternalServerError, "Internal server error")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -162,6 +165,8 @@ func (r *UserController) GetAll(c *gin.Context) {
// @Param request body requests.PutUserRequest true "User data" // @Param request body requests.PutUserRequest true "User data"
// @Success 200 {object} responses.UserResponse // @Success 200 {object} responses.UserResponse
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /user/{id} [put] // @Router /user/{id} [put]
func (r *UserController) Put(c *gin.Context) { func (r *UserController) Put(c *gin.Context) {
var request requests.PutUserRequest var request requests.PutUserRequest
@ -170,14 +175,14 @@ func (r *UserController) Put(c *gin.Context) {
id, err := uuid.Parse(id_path) id, err := uuid.Parse(id_path)
if err != nil { if err != nil {
log.Println("User id error: ", err) log.Println("User id error: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, "Invalid user ID")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
if err := c.BindJSON(&request); err != nil { if err := c.BindJSON(&request); err != nil {
log.Println("User request error: ", err) log.Println("User request error: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, err.Error())
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -198,8 +203,7 @@ func (r *UserController) Put(c *gin.Context) {
user, err := r.service.Update(cmd) user, err := r.service.Update(cmd)
if err != nil { if err != nil {
log.Println("User service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusInternalServerError, "Internal server error")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -215,6 +219,8 @@ func (r *UserController) Put(c *gin.Context) {
// @Param id path string true "User id" // @Param id path string true "User id"
// @Success 200 // @Success 200
// @Failure 400 {object} responses.ErrorResponse // @Failure 400 {object} responses.ErrorResponse
// @Failure 404 {object} responses.ErrorResponse
// @Failure 500 {object} responses.ErrorResponse
// @Router /user/{id} [delete] // @Router /user/{id} [delete]
func (r *UserController) Delete(c *gin.Context) { func (r *UserController) Delete(c *gin.Context) {
id_path := c.Param("id") id_path := c.Param("id")
@ -222,7 +228,7 @@ func (r *UserController) Delete(c *gin.Context) {
id, err := uuid.Parse(id_path) id, err := uuid.Parse(id_path)
if err != nil { if err != nil {
log.Println("User id error: ", err) log.Println("User id error: ", err)
resp := responses.CreateErrorResponse(http.StatusBadRequest, "Bad request") resp := responses.CreateErrorResponse(http.StatusBadRequest, "Invalid user id")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }
@ -232,8 +238,7 @@ func (r *UserController) Delete(c *gin.Context) {
} }
if err := r.service.Delete(cmd); err != nil { if err := r.service.Delete(cmd); err != nil {
log.Println("User service error: ", err) resp := utils.HandleError(err)
resp := responses.CreateErrorResponse(http.StatusNotFound, "User not found")
c.JSON(resp.ErrorCode, resp) c.JSON(resp.ErrorCode, resp)
return return
} }

View file

@ -0,0 +1,30 @@
package utils
import (
ie "58team_blog/internal/application/errors"
"58team_blog/internal/interfaces/api/responses"
"errors"
"log"
"net/http"
)
func HandleError(err error) responses.ErrorResponse {
var errorCode int
errorMsg := err.Error()
log.Println(err)
if errors.Is(&ie.ValidationError{}, err) {
errorCode = http.StatusBadRequest
} else if errors.Is(&ie.NotFoundError{}, err) {
errorCode = http.StatusNotFound
} else if errors.Is(&ie.AlreadyExistsError{}, err) {
errorCode = http.StatusConflict
} else if errors.Is(&ie.DBError{}, err) {
errorCode = http.StatusInternalServerError
} else {
errorCode = http.StatusInternalServerError
}
return responses.CreateErrorResponse(errorCode, errorMsg)
}