feat(error): added first steps for custom errors
All checks were successful
Gitea Build Check / Build (push) Successful in 11m2s

Signed-off-by: SoXX <soxx@fenpa.ws>
This commit is contained in:
SoXX 2024-06-25 16:02:08 +02:00
parent c246f661ff
commit 63e74219ed
3 changed files with 44 additions and 8 deletions

19
error/database.go Normal file
View File

@ -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"
}

7
error/validation.go Normal file
View File

@ -0,0 +1,7 @@
package error
type MissingAnthrovePostIDError struct{}
func (e *MissingAnthrovePostIDError) Error() string {
return "AnthrovePostID is empty"
}

View File

@ -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