From b87a05c39ef588a7a47a0d9d64f0f9084d4f169f Mon Sep 17 00:00:00 2001 From: Matthew Dillon Date: Wed, 24 Jun 2015 22:37:47 -0800 Subject: [PATCH] Fix handling of validation error --- helpers.go | 1 + users.go | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/helpers.go b/helpers.go index 011cae6..427ad07 100644 --- a/helpers.go +++ b/helpers.go @@ -12,6 +12,7 @@ import ( var ( ErrMustProvideOptions = errors.New("Must provide necessary options") ErrMustProvideOptionsJSON = newJSONError(ErrMustProvideOptions, http.StatusBadRequest) + StatusUnprocessableEntity = 422 ) // ListOptions specifies general pagination options for fetching a list of results diff --git a/users.go b/users.go index e91d926..423037d 100644 --- a/users.go +++ b/users.go @@ -43,7 +43,9 @@ type UserValidation struct { } func (uv UserValidation) Error() string { - errs, err := json.Marshal(uv) + errs, err := json.Marshal(struct { + UserValidation `json:"errors"` + }{uv}) if err != nil { return err.Error() } @@ -74,7 +76,7 @@ func (u UserService) unmarshal(b []byte) (entity, error) { return uj.User, err } -func (u *User) validate() *appError { +func (u *User) validate() error { var uv UserValidation validationError := false @@ -84,8 +86,7 @@ func (u *User) validate() *appError { } if validationError { - errs, _ := json.Marshal(uv) - return newJSONError(errors.New(string(errs)), http.StatusBadRequest) + return uv } 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 { user := (*e).(*User) if err := user.validate(); err != nil { - return err + return &appError{Error: err, Status: StatusUnprocessableEntity} } ct := currentTime() user.CreatedAt = ct