Added custom error type for user does not exist

This commit is contained in:
konrad 2018-01-23 15:19:39 +01:00 committed by kolaente
parent aaf5ca0ceb
commit 323f4c7ff4
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
4 changed files with 64 additions and 2 deletions

View File

@ -36,3 +36,18 @@ func IsErrNoUsername(err error) bool {
func (err ErrNoUsername) Error() string {
return fmt.Sprintf("you need to specify a username [user id: %d]", err.UserID)
}
// ErrUserDoesNotExist represents a "UsernameAlreadyExists" kind of error.
type ErrUserDoesNotExist struct {
UserID int64
}
// IsErrNoUsername checks if an error is a ErrUsernameExists.
func IsErrUserDoesNotExist(err error) bool {
_, ok := err.(ErrUserDoesNotExist)
return ok
}
func (err ErrUserDoesNotExist) Error() string {
return fmt.Sprintf("this user does not exist [user id: %d]", err.UserID)
}

View File

@ -68,7 +68,7 @@ func CheckUserCredentials(u *UserLogin) (User, error) {
}
if !exists {
return User{}, fmt.Errorf("user does not exist")
return User{}, ErrUserDoesNotExist{}
}
// Check the users password

View File

@ -57,6 +57,10 @@ func UpdateUser(user User) (updatedUser User, err error) {
// Check if it exists
theUser, exists, err := GetUserByID(user.ID)
if err != nil {
return User{}, err
}
if exists {
user.Password = theUser.Password // set the password to the one in the database to not accedently resetting it
@ -66,9 +70,16 @@ func UpdateUser(user User) (updatedUser User, err error) {
if err != nil {
return User{}, err
}
// Get the newly updated user
updatedUser, _, err = GetUserByID(user.ID)
if err != nil {
return User{}, err
}
return updatedUser, nil
}
return User{}, fmt.Errorf("This user does not exist")
return User{}, ErrUserDoesNotExist{user.ID}
}
// UpdateUserPassword updates the password of a user

View File

@ -0,0 +1,36 @@
package v1
import (
"github.com/labstack/echo"
"net/http"
"strconv"
"git.mowie.cc/konrad/Library/models"
)
func UserShow(c echo.Context) error {
user := c.Param("id")
if user == "" {
return c.JSON(http.StatusBadRequest, models.Message{"User ID cannot be empty."})
}
// Make int
userID, err := strconv.ParseInt(user, 10, 64)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error getting user infos."})
}
// Get User Infos
userInfos, exists, err := models.GetUserByID(userID)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error getting user infos."})
}
// Check if it exists
if !exists {
return c.JSON(http.StatusNotFound, models.Message{"User not found."})
}
return c.JSON(http.StatusOK, userInfos)
}