Added custom error type for no book title
This commit is contained in:
parent
c3cfc73840
commit
dec5db7649
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -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"})
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue