Skip to content

Commit

Permalink
add an example of SetContextErrorHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
kataras committed Apr 12, 2022
1 parent ae828d8 commit 3582427
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
14 changes: 11 additions & 3 deletions _examples/response-writer/write-rest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}

Expand Down Expand Up @@ -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)
}
6 changes: 3 additions & 3 deletions context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down

0 comments on commit 3582427

Please sign in to comment.