Fix handling of validation error

This commit is contained in:
Matthew Dillon 2015-06-24 22:37:47 -08:00
parent 384002155a
commit b87a05c39e
2 changed files with 7 additions and 5 deletions

View file

@ -12,6 +12,7 @@ import (
var ( var (
ErrMustProvideOptions = errors.New("Must provide necessary options") ErrMustProvideOptions = errors.New("Must provide necessary options")
ErrMustProvideOptionsJSON = newJSONError(ErrMustProvideOptions, http.StatusBadRequest) ErrMustProvideOptionsJSON = newJSONError(ErrMustProvideOptions, http.StatusBadRequest)
StatusUnprocessableEntity = 422
) )
// ListOptions specifies general pagination options for fetching a list of results // ListOptions specifies general pagination options for fetching a list of results

View file

@ -43,7 +43,9 @@ type UserValidation struct {
} }
func (uv UserValidation) Error() string { func (uv UserValidation) Error() string {
errs, err := json.Marshal(uv) errs, err := json.Marshal(struct {
UserValidation `json:"errors"`
}{uv})
if err != nil { if err != nil {
return err.Error() return err.Error()
} }
@ -74,7 +76,7 @@ func (u UserService) unmarshal(b []byte) (entity, error) {
return uj.User, err return uj.User, err
} }
func (u *User) validate() *appError { func (u *User) validate() error {
var uv UserValidation var uv UserValidation
validationError := false validationError := false
@ -84,8 +86,7 @@ func (u *User) validate() *appError {
} }
if validationError { if validationError {
errs, _ := json.Marshal(uv) return uv
return newJSONError(errors.New(string(errs)), http.StatusBadRequest)
} }
return nil return nil
} }
@ -137,7 +138,7 @@ func (u UserService) update(id int64, e *entity, claims Claims) *appError {
func (u UserService) create(e *entity, claims Claims) *appError { func (u UserService) create(e *entity, claims Claims) *appError {
user := (*e).(*User) user := (*e).(*User)
if err := user.validate(); err != nil { if err := user.validate(); err != nil {
return err return &appError{Error: err, Status: StatusUnprocessableEntity}
} }
ct := currentTime() ct := currentTime()
user.CreatedAt = ct user.CreatedAt = ct