From 63e74219ed245b6eabe1c5d8baec540d8aba31da Mon Sep 17 00:00:00 2001 From: SoXX Date: Tue, 25 Jun 2024 16:02:08 +0200 Subject: [PATCH] feat(error): added first steps for custom errors Signed-off-by: SoXX --- error/database.go | 19 +++++++++++++++++++ error/validation.go | 7 +++++++ internal/postgres/post.go | 26 ++++++++++++++++++-------- 3 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 error/database.go create mode 100644 error/validation.go diff --git a/error/database.go b/error/database.go new file mode 100644 index 0000000..c842614 --- /dev/null +++ b/error/database.go @@ -0,0 +1,19 @@ +package error + +type EntityAlreadyExists struct{} + +type NoDataWritten struct{} + +type NoDataFound struct{} + +func (e *EntityAlreadyExists) Error() string { + return "EntityAlreadyExists error" +} + +func (e *NoDataWritten) Error() string { + return "NoDataWritten error" +} + +func (e *NoDataFound) Error() string { + return "NoDataFound error" +} diff --git a/error/validation.go b/error/validation.go new file mode 100644 index 0000000..b6b4245 --- /dev/null +++ b/error/validation.go @@ -0,0 +1,7 @@ +package error + +type MissingAnthrovePostIDError struct{} + +func (e *MissingAnthrovePostIDError) Error() string { + return "AnthrovePostID is empty" +} diff --git a/internal/postgres/post.go b/internal/postgres/post.go index 2dde49a..ffe74be 100644 --- a/internal/postgres/post.go +++ b/internal/postgres/post.go @@ -3,16 +3,24 @@ package postgres import ( "context" "errors" - "fmt" + + error2 "git.dragse.it/anthrove/otter-space-sdk/error" "git.dragse.it/anthrove/otter-space-sdk/pkg/models" log "github.com/sirupsen/logrus" "gorm.io/gorm" ) func CreatePost(ctx context.Context, db *gorm.DB, anthrovePost *models.Post) error { - err := db.WithContext(ctx).Create(&anthrovePost).Error - if err != nil { - return err + result := db.WithContext(ctx).Create(&anthrovePost) + + if result.RowsAffected == 0 { + return &error2.NoDataWritten{} + } + + if result.Error != nil { + if errors.Is(result.Error, gorm.ErrDuplicatedKey) { + return &error2.EntityAlreadyExists{} + } } log.WithFields(log.Fields{ @@ -25,13 +33,15 @@ func CreatePost(ctx context.Context, db *gorm.DB, anthrovePost *models.Post) err func GetPostByAnthroveID(ctx context.Context, db *gorm.DB, anthrovePostID models.AnthrovePostID) (*models.Post, error) { if anthrovePostID == "" { - return nil, fmt.Errorf("anthrovePostID is required") + return nil, &error2.MissingAnthrovePostIDError{} } var post models.Post - err := db.WithContext(ctx).First(&post, "id = ?", anthrovePostID).Error - if err != nil { - return nil, err + result := db.WithContext(ctx).First(&post, "id = ?", anthrovePostID) + if result.Error != nil { + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + return nil, &error2.NoDataFound{} + } } return &post, nil