Added custom error type for no book title

This commit is contained in:
konrad 2018-01-24 13:13:55 +01:00 committed by kolaente
parent c3cfc73840
commit dec5db7649
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
4 changed files with 24 additions and 5 deletions

View File

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

View File

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

View File

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

View File

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