Added custom error type for no username provided

This commit is contained in:
konrad 2018-01-23 14:52:03 +01:00 committed by kolaente
parent f7314b439f
commit aaf5ca0ceb
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
5 changed files with 30 additions and 3 deletions

View File

@ -2,6 +2,10 @@ package models
import "fmt"
// =====================
// User Operation Errors
// =====================
// ErrUsernameExists represents a "UsernameAlreadyExists" kind of error.
type ErrUsernameExists struct {
UserID int64
@ -17,3 +21,18 @@ func IsErrUsernameExists(err error) bool {
func (err ErrUsernameExists) Error() string {
return fmt.Sprintf("a user with this username does already exist [user id: %d, username: %s]", err.UserID, err.Username)
}
// ErrNoUsername represents a "UsernameAlreadyExists" kind of error.
type ErrNoUsername struct {
UserID int64
}
// IsErrNoUsername checks if an error is a ErrUsernameExists.
func IsErrNoUsername(err error) bool {
_, ok := err.(ErrNoUsername)
return ok
}
func (err ErrNoUsername) Error() string {
return fmt.Sprintf("you need to specify a username [user id: %d]", err.UserID)
}

View File

@ -42,7 +42,7 @@ func (User) TableName() string {
// GetUserByID gets informations about a user by its ID
func GetUserByID(id int64) (user User, exists bool, err error) {
// Apparently xorm does otherwise look for all users but return only one, which leads to returing one even if the ID is 0
if user.ID == 0 {
if id == 0 {
return User{}, false, nil
}

View File

@ -52,7 +52,7 @@ func hashPassword(password string) (string, error) {
func UpdateUser(user User) (updatedUser User, err error) {
// Check if we have at least a username
if user.Username == "" {
return User{}, fmt.Errorf("you need to specify at least a username and a password")
return User{}, ErrNoUsername{user.ID}
}
// Check if it exists

View File

@ -57,9 +57,16 @@ func UserAddOrUpdate(c echo.Context) error {
}
if err != nil {
// Check for user already exists
if models.IsErrUsernameExists(err) {
return c.JSON(http.StatusBadRequest, models.Message{"A user with this username already exists"})
return c.JSON(http.StatusBadRequest, models.Message{"A user with this username already exists."})
}
// Check for no username provided
if models.IsErrNoUsername(err) {
return c.JSON(http.StatusBadRequest, models.Message{"Please specify a username."})
}
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}

View File

@ -110,6 +110,7 @@ func RegisterRoutes(e *echo.Echo) {
a.GET("/users", apiv1.UsersList)
a.PUT("/users", apiv1.UserAddOrUpdate)
a.POST("/users/:id", apiv1.UserAddOrUpdate)
// Manage Users