diff --git a/models/book_test.go b/models/book_test.go index 70b8ec2..02f6e6e 100644 --- a/models/book_test.go +++ b/models/book_test.go @@ -88,6 +88,7 @@ func TestAddOrUpdateBook(t *testing.T) { // Pass an empty Book to see if it fails _, err = AddOrUpdateBook(Book{}) assert.Error(t, err) + assert.True(t, IsErrBookTitleCannotBeEmpty(err)) // Update the book testbook.ID = book1.ID diff --git a/models/books_add_update.go b/models/books_add_update.go index c4e68b9..1b7e341 100644 --- a/models/books_add_update.go +++ b/models/books_add_update.go @@ -1,7 +1,5 @@ package models -import "fmt" - /** ::USAGE:: @@ -21,8 +19,8 @@ sie in die Datenbank eingetragen und mit dem Buch verknüpft. func AddOrUpdateBook(book Book) (newBook Book, err error) { // Check if we have at least a booktitle when we're inserting a new book - if book.Title == "" && book.ID == 0 { - return Book{}, fmt.Errorf("the book should at least have a title") + if book.Title == ""{ + return Book{}, ErrBookTitleCannotBeEmpty{} } // Take Publisher, check if it exists. If not, insert it diff --git a/models/error.go b/models/error.go index 89aad21..4e4b627 100644 --- a/models/error.go +++ b/models/error.go @@ -91,4 +91,17 @@ func (err ErrItemTitleCannotBeEmpty) Error() string { return fmt.Sprintf("title cannot be empty") } +// ErrBookTitleCannotBeEmpty represents a "ErrBookTitleCannotBeEmpty" kind of error. +type ErrBookTitleCannotBeEmpty struct {} + +// ErrBookTitleCannotBeEmpty checks if an error is a ErrBookTitleCannotBeEmpty. +func IsErrBookTitleCannotBeEmpty(err error) bool { + _, ok := err.(ErrBookTitleCannotBeEmpty) + return ok +} + +func (err ErrBookTitleCannotBeEmpty) Error() string { + return fmt.Sprintf("the book should at least have a title") +} + diff --git a/routes/api/v1/books_add_update.go b/routes/api/v1/books_add_update.go index 01a66cd..abe18bb 100644 --- a/routes/api/v1/books_add_update.go +++ b/routes/api/v1/books_add_update.go @@ -7,6 +7,7 @@ import ( "net/http" "strconv" "strings" + "fmt" ) // BookAddOrUpdate is the handler to add a book @@ -62,9 +63,15 @@ func BookAddOrUpdate(c echo.Context) error { newBook, err := models.AddOrUpdateBook(*datBook) if err != nil { + fmt.Println(err) if models.IsErrAuthorCannotBeEmpty(err) { - return c.JSON(http.StatusInternalServerError, models.Message{"Id cannot be 0"}) + return c.JSON(http.StatusInternalServerError, models.Message{"Id cannot be 0."}) } + + 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.StatusInternalServerError, models.Message{"Error"}) }