From 3582427df6eb049e0c0696cc32be0ab0f0566b94 Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Wed, 13 Apr 2022 01:11:31 +0300 Subject: [PATCH] add an example of SetContextErrorHandler --- _examples/response-writer/write-rest/main.go | 14 +++++++++++--- context/context.go | 6 +++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/_examples/response-writer/write-rest/main.go b/_examples/response-writer/write-rest/main.go index db9e9bfa..160144f2 100644 --- a/_examples/response-writer/write-rest/main.go +++ b/_examples/response-writer/write-rest/main.go @@ -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) +} diff --git a/context/context.go b/context/context.go index cd497fab..fe7fa6f3 100644 --- a/context/context.go +++ b/context/context.go @@ -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))