add an example of SetContextErrorHandler

This commit is contained in:
Gerasimos (Makis) Maropoulos 2022-04-13 01:11:31 +03:00
parent ae828d8db9
commit 3582427df6
No known key found for this signature in database
GPG Key ID: 66FCC29BD385FCA6
2 changed files with 14 additions and 6 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/xml"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/x/errors"
)
// User example struct for json and msgpack.
@ -29,15 +30,16 @@ type ExampleYAML struct {
func main() {
app := iris.New()
// Optionally, set a custom handler for JSON, JSONP, Protobuf, MsgPack, YAML, Markdown...
// write errors.
app.SetContextErrorHandler(new(errorHandler))
// Read
app.Post("/decode", func(ctx iris.Context) {
// Read https://github.com/kataras/iris/blob/master/_examples/request-body/read-json/main.go as well.
var user User
err := ctx.ReadJSON(&user)
if err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.Writef("unable to read body: %s\nbody is empty: %v", err.Error(), iris.IsErrEmptyJSON(err))
errors.InvalidArgument.Details(ctx, "unable to parse body", err.Error())
return
}
@ -165,3 +167,9 @@ func main() {
// if passed to the `Run` then it will not print its passed error as an actual server error.
app.Listen(":8080", iris.WithOptimizations)
}
type errorHandler struct{}
func (h *errorHandler) HandleContextError(ctx iris.Context, err error) {
errors.Internal.Err(ctx, err)
}

View File

@ -3966,9 +3966,9 @@ func WriteJSON(ctx stdContext.Context, writer io.Writer, v interface{}, options
}
// See https://golang.org/src/strings/builder.go#L45
func bytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// func bytesToString(b []byte) string {
// return *(*string)(unsafe.Pointer(&b))
// }
func stringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&s))