Added custom error type when a publisher has no name
the build failed Details

This commit is contained in:
konrad 2018-01-24 23:55:10 +01:00 committed by kolaente
parent 815ec40696
commit 3d27bb1438
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
5 changed files with 23 additions and 4 deletions

View File

@ -117,3 +117,15 @@ func (err ErrCouldNotGetUserID) Error() string {
return fmt.Sprintf("could not get user ID")
}
// ErrNoPublisherName represents a "ErrNoPublisherName" kind of error.
type ErrNoPublisherName struct {}
// IsErrNoPublisherName checks if an error is a ErrNoPublisherName.
func IsErrNoPublisherName(err error) bool {
_, ok := err.(ErrNoPublisherName)
return ok
}
func (err ErrNoPublisherName) Error() string {
return fmt.Sprintf("you need at least a name to insert a new publisher")
}

View File

@ -44,6 +44,7 @@ func TestAddOrUpdatePublisher(t *testing.T) {
// Pass an empty publisher to see if it fails
_, err = AddOrUpdatePublisher(Publisher{})
assert.Error(t, err)
assert.True(t, IsErrNoPublisherName(err))
// Update the publisher
testpublisher.ID = publisher1.ID

View File

@ -1,12 +1,10 @@
package models
import "fmt"
// AddOrUpdatePublisher adds or updates a publisher from a publisher struct
func AddOrUpdatePublisher(publisher Publisher) (newPublisher Publisher, err error) {
if publisher.ID == 0 {
if publisher.Name == "" { // Only insert it if the name is not empty
return Publisher{}, fmt.Errorf("You need at least a name to insert a new publisher")
return Publisher{}, ErrNoPublisherName{}
}
_, err = x.Insert(&publisher)

View File

@ -67,7 +67,11 @@ func BookAddOrUpdate(c echo.Context) error {
}
if models.IsErrBookTitleCannotBeEmpty(err) {
return c.JSON(http.StatusBadRequest, models.Message{"You need to provide at least a Title for the book."})
return c.JSON(http.StatusBadRequest, models.Message{"You need to provide at least a title for the book."})
}
if models.IsErrNoPublisherName(err) {
return c.JSON(http.StatusBadRequest, models.Message{"You need to provide at least a name to insert a new publisher."})
}
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})

View File

@ -58,6 +58,10 @@ func PublisherAddOrUpdate(c echo.Context) error {
newPublisher, err := models.AddOrUpdatePublisher(*datPublisher)
if err != nil {
if models.IsErrNoPublisherName(err) {
return c.JSON(http.StatusBadRequest, models.Message{"You need to provide at least a name to insert a new publisher."})
}
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}