Skip to content

Commit

Permalink
feat(validate): support validate struct error and handler return GError
Browse files Browse the repository at this point in the history
  • Loading branch information
cutedogspark committed Apr 25, 2018
1 parent 0afcbaf commit 6e59660
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 36 deletions.
23 changes: 22 additions & 1 deletion Gopkg.lock

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

4 changes: 4 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@
[prune]
go-tests = true
unused-packages = true

[[constraint]]
name = "gopkg.in/go-playground/validator.v9"
version = "9.15.0"
68 changes: 40 additions & 28 deletions errhandler.go
Original file line number Diff line number Diff line change
@@ -1,40 +1,52 @@
package ctx

import (
"encoding/json"
"fmt"
"net/http"
"strings"

"github.com/labstack/echo"
"github.com/pkg/errors"
"gopkg.in/go-playground/validator.v9"
)

func HTTPErrorHandler(err error, c echo.Context) {

r := CustomCtx{c}
code := http.StatusInternalServerError
var msg interface{}
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
msg = he.Message
}
if err := r.Resp(code).Error(fmt.Sprintf("%v", msg)).Code(code).Do(); err != nil {
c.Logger().Error(err)
}

/*
errDate := sri.NewErrors()
errDate.Add(msg)
if err := r.Resp(code).Error(fmt.Sprintf("%v", msg)).Code(code).Errors(errDate.Error()).Do(); err != nil {
c.Logger().Error(err)
if he, ok := err.(*GErrCall); ok {
err = errors.WithStack(he)
b, _ := json.Marshal(he.ResponseParams)
c.JSONBlob(he.HttpStatus, b)
} else if he, ok := err.(*GError); ok {
err = errors.WithStack(he)
gErrs := CustomCtx{}.GResp().Errors(he)
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(gErrs.HttpStatus, b)
} else if he, ok := err.(*echo.HTTPError); ok {
// warp echo error struct
err = errors.WithStack(he)
gErrs := CustomCtx{}.GResp().Errors(&GError{
Code: uint(he.Code),
Message: fmt.Sprintf("%+v", he.Message),
})
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(gErrs.HttpStatus, b)
} else if _, ok := err.(*validator.InvalidValidationError); !ok {
var errMsg []string
for _, err := range err.(validator.ValidationErrors) {
errMsg = append(errMsg, fmt.Sprintf("%s:%s", err.Field(), err.ActualTag()))
}
{
"apiVersion": "v1",
"error": {
"code": 404,
"message": "Not Found",
"errors": [
"Not Found"
]
}
}
*/
gErrs := CustomCtx{}.GResp(http.StatusBadRequest).Errors(&GError{Code: http.StatusBadRequest, Message: strings.Join(errMsg, ",")})
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(gErrs.HttpStatus, b)
} else {
// define unknown error message
err = errors.New("unknown error")
gErrs := CustomCtx{}.GResp().Errors(&GError{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(gErrs.HttpStatus, b)
}
c.Logger().Error(err)
}
69 changes: 62 additions & 7 deletions example/ErrorHandler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,69 @@ import (
"encoding/json"
"fmt"
"net/http"
"strings"

"github.com/cutedogspark/echo-custom-context"
"github.com/labstack/echo"
"github.com/pkg/errors"
"gopkg.in/go-playground/validator.v9"
)

func HTTPErrorHandler(err error, c echo.Context) {
if he, ok := err.(*ctx.GErrCall); ok {
err = errors.WithStack(he)
b, _ := json.Marshal(he.ResponseParams)
c.JSONBlob(he.HttpStatus, b)
} else if he, ok := err.(*ctx.GError); ok {
err = errors.WithStack(he)
gErrs := ctx.CustomCtx{}.GResp().Errors(he)
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(gErrs.HttpStatus, b)
} else if he, ok := err.(*echo.HTTPError); ok {
// warp echo error struct
err = errors.WithStack(he)
gCtx := ctx.CustomCtx{}
gErrs := gCtx.GResp().Errors(&ctx.GError{
gErrs := ctx.CustomCtx{}.GResp().Errors(&ctx.GError{
Code: uint(he.Code),
Message: fmt.Sprintf("%+v", he.Message),
})
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(he.Code, b)
c.JSONBlob(gErrs.HttpStatus, b)
} else if _, ok := err.(*validator.InvalidValidationError); !ok {
var errMsg []string
for _, err := range err.(validator.ValidationErrors) {
errMsg = append(errMsg, fmt.Sprintf("%s:%s", err.Field(), err.ActualTag()))
}
gErrs := ctx.CustomCtx{}.GResp(http.StatusBadRequest).Errors(&ctx.GError{Code: http.StatusBadRequest, Message: strings.Join(errMsg, ",")})
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(gErrs.HttpStatus, b)
} else {
// define unknown error message
err = errors.New("unknown error")
gCtx := ctx.CustomCtx{}
gErrs := gCtx.GResp().Errors(&ctx.GError{
gErrs := ctx.CustomCtx{}.GResp().Errors(&ctx.GError{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
b, _ := json.Marshal(gErrs.ResponseParams)
c.JSONBlob(he.Code, b)
c.JSONBlob(gErrs.HttpStatus, b)
}
c.Logger().Error(err)
}

type (
CustomValidator struct {
validator *validator.Validate
}
)

func (cv *CustomValidator) Validate(i interface{}) error {
return cv.validator.Struct(i)
}

func main() {

e := echo.New()
e.HideBanner = true
e.Validator = &CustomValidator{validator: validator.New()}
e.HTTPErrorHandler = HTTPErrorHandler
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
Expand All @@ -55,7 +79,7 @@ func main() {
return c.(ctx.CustomCtx).GResp(http.StatusOK).Data("Service").Out()
})

e.GET("/gerr", func(c echo.Context) error {
e.GET("/gerrs", func(c echo.Context) error {
gerrs := ctx.NewGErrors().Append(&ctx.GError{
Code: 40000001,
Domain: "Calendar",
Expand All @@ -73,9 +97,24 @@ func main() {
LocationType: "parameter",
Location: "part",
})

return c.(ctx.CustomCtx).GResp().Errors(*gerrs...).Do()
})

e.GET("/gerr", func(c echo.Context) error {
gErr := &ctx.GError{
Code: 40000001,
Domain: "Calendar",
Reason: "ResourceNotFoundException",
Message: "Resources is not exist",
LocationType: "database query",
Location: "query",
ExtendedHelp: "http://help-link",
SendReport: "http://report.dajui.com/",
}
return gErr
})

e.GET("/echo-error", func(c echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, "default echo error handler")
})
Expand All @@ -84,6 +123,22 @@ func main() {
return errors.New("Goodbye")
})

e.GET("/validate-error", func(c echo.Context) error {

type req struct {
App string `form:"app" validate:"required,numeric"`
Key string `form:"key" validate:"required"`
ClientId int `form:"clientid" validate:"required"`
}
in := new(req)
in.App = "God"

if err := c.Validate(in); err != nil {
return err
}
return c.(ctx.CustomCtx).GResp(http.StatusOK).Data("validate sucess").Out()
})

// Start server
e.Logger.Fatal(e.Start(":1234"))
}

0 comments on commit 6e59660

Please sign in to comment.