Skip to content

Commit

Permalink
Add new x/errors/validation package to make your life even more easie…
Browse files Browse the repository at this point in the history
…r (using Generics)
  • Loading branch information
kataras committed Jan 7, 2024
1 parent 8f2deb6 commit 104bea0
Show file tree
Hide file tree
Showing 14 changed files with 443 additions and 282 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Developers are not forced to upgrade if they don't really need it. Upgrade whene

Changes apply to `main` branch.

- Simplify how validation errors on `/x/errors` package works. A new `x/errors/validation` sub-package added to make your life easier (using the powerful Generics feature).
- Add `x/errors.OK`, `Create`, `NoContent` and `NoContentOrNotModified` package-level generic functions as custom service method caller helpers. Example can be found [here](_examples/routing/http-wire-errors/service/main.go).
- Add `x/errors.ReadPayload`, `ReadQuery`, `ReadPaginationOptions`, `Handle`, `HandleCreate`, `HandleCreateResponse`, `HandleUpdate` and `HandleDelete` package-level functions as helpers for common actions.
- Add `x/jsonx.GetSimpleDateRange(date, jsonx.WeekRange, time.Monday, time.Sunday)` which returns all dates between the given range and start/end weekday values for WeekRange.
Expand Down
3 changes: 1 addition & 2 deletions _examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@
* [Basic](routing/basic/main.go)
* [Custom HTTP Errors](routing/http-errors/main.go)
* [HTTP Wire Errors](routing/http-wire-errors/main.go) **NEW**
* [Custom Validation Errors](routing/http-wire-errors/custom-validation-errors/main.go)
* [Service](routing/http-wire-errors/service/main.go) **NEW**
* [Service and Validation](routing/http-wire-errors/service/main.go) **NEW**
* [Not Found - Intelligence](routing/intelligence/main.go)
* [Not Found - Suggest Closest Paths](routing/intelligence/manual/main.go)
* [Dynamic Path](routing/dynamic-path/main.go)
Expand Down
1 change: 0 additions & 1 deletion _examples/README_ZH_HANT.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
- [Basic](routing/basic/main.go)
- [Custom HTTP Errors](routing/http-errors/main.go)
- [HTTP Wire Errors](routing/http-wire-errors/main.go) **新範例**
- [Custom Validation Errors](routing/http-wire-errors/custom-validation-errors/main.go)
- [Not Found - Intelligence](routing/intelligence/main.go)
- [Not Found - Suggest Closest Paths](routing/intelligence/manual/main.go)
- [Dynamic Path](routing/dynamic-path/main.go)
Expand Down
119 changes: 0 additions & 119 deletions _examples/routing/http-wire-errors/custom-validation-errors/main.go

This file was deleted.

62 changes: 57 additions & 5 deletions _examples/routing/http-wire-errors/service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import (

"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/x/errors"
"github.com/kataras/iris/v12/x/errors/validation"
)

func main() {
app := iris.New()

service := new(myService)

app.Post("/", createHandler(service))
app.Get("/", listHandler(service))
app.Delete("/{id:string}", deleteHandler(service))
Expand Down Expand Up @@ -70,16 +71,65 @@ type (
myService struct{}

CreateRequest struct {
Fullname string
Fullname string `json:"fullname"`
Age int `json:"age"`
Hobbies []string `json:"hobbies"`
}

CreateResponse struct {
ID string
Firstname string
Lastname string
ID string `json:"id"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Age int `json:"age"`
Hobbies []string `json:"hobbies"`
}
)

// ValidateContext implements the errors.ContextValidator interface.
// It validates the request body and returns an error if the request body is invalid.
// You can also alter the "r" CreateRequest before calling the service method,
// e.g. give a default value to a field if it's empty or set an ID based on a path parameter.
func (r *CreateRequest) ValidateContext(ctx iris.Context) error {
// To pass custom validation functions:
// return validation.Join(
// validation.String("fullname", r.Fullname).Func(customStringFuncHere),
// OR
// validation.Field("any_field", r.AnyFieldValue).Func(customAnyFuncHere))
return validation.Join(
validation.String("fullname", r.Fullname).NotEmpty().Fullname().Length(3, 50),
validation.Number("age", r.Age).InRange(18, 130),
validation.Slice("hobbies", r.Hobbies).Length(1, 10),
)

/* Example Output:
{
"http_error_code": {
"canonical_name": "INVALID_ARGUMENT",
"status": 400
},
"message": "validation failure",
"details": "fields were invalid",
"validation": [
{
"field": "fullname",
"value": "",
"reason": "must not be empty, must contain first and last name, must be between 3 and 50 characters"
},
{
"field": "age",
"value": 0,
"reason": "must be in range of [18, 130]"
},
{
"field": "hobbies",
"value": null,
"reason": "must be between 1 and 10 elements"
}
]
}
*/
}

func (s *myService) Create(ctx context.Context, in CreateRequest) (CreateResponse, error) {
arr := strings.Split(in.Fullname, " ")
firstname, lastname := arr[0], arr[1]
Expand All @@ -89,6 +139,8 @@ func (s *myService) Create(ctx context.Context, in CreateRequest) (CreateRespons
ID: id,
Firstname: firstname,
Lastname: lastname,
Age: in.Age,
Hobbies: in.Hobbies,
}
return resp, nil // , errors.New("create: test error")
}
Expand Down
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,17 @@ require (
github.com/mailgun/raymond/v2 v2.0.48
github.com/mailru/easyjson v0.7.7
github.com/microcosm-cc/bluemonday v1.0.26
github.com/redis/go-redis/v9 v9.3.1
github.com/redis/go-redis/v9 v9.4.0
github.com/schollz/closestmatch v2.1.0+incompatible
github.com/shirou/gopsutil/v3 v3.23.12
github.com/tdewolff/minify/v2 v2.20.10
github.com/tdewolff/minify/v2 v2.20.12
github.com/vmihailenco/msgpack/v5 v5.4.1
github.com/yosssi/ace v0.0.5
go.etcd.io/bbolt v1.3.8
golang.org/x/crypto v0.17.0
golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc
golang.org/x/net v0.19.0
golang.org/x/sys v0.15.0
golang.org/x/sys v0.16.0
golang.org/x/text v0.14.0
golang.org/x/time v0.5.0
google.golang.org/protobuf v1.32.0
Expand Down Expand Up @@ -107,7 +108,6 @@ require (
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
moul.io/http2curl/v2 v2.3.0 // indirect
)
18 changes: 10 additions & 8 deletions go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 29 additions & 5 deletions x/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,21 @@ func HandleError(ctx *context.Context, err error) bool {
return true
}

if vErrs, ok := AsValidationErrors(err); ok {
InvalidArgument.Data(ctx, "validation failure", vErrs)
if vErr, ok := err.(ValidationError); ok {
if vErr == nil {
return false // consider as not error for any case, this should never happen.
}

InvalidArgument.Validation(ctx, vErr)
return true
}

if vErrs, ok := err.(ValidationErrors); ok {
if len(vErrs) == 0 {
return false // consider as not error for any case, this should never happen.
}

InvalidArgument.Validation(ctx, vErrs...)
return true
}

Expand Down Expand Up @@ -283,9 +296,20 @@ func (e ErrorCodeName) Err(ctx *context.Context, err error) {
return
}

if validationErrors, ok := AsValidationErrors(err); ok {
e.validation(ctx, validationErrors)
return
if vErr, ok := err.(ValidationError); ok {
if vErr == nil {
return // consider as not error for any case, this should never happen.
}

e.Validation(ctx, vErr)
}

if vErrs, ok := err.(ValidationErrors); ok {
if len(vErrs) == 0 {
return // consider as not error for any case, this should never happen.
}

e.Validation(ctx, vErrs...)
}

// If it's already an Error type then send it directly.
Expand Down
Loading

0 comments on commit 104bea0

Please sign in to comment.