mirror of
https://github.com/kataras/iris.git
synced 2025-03-15 17:36:29 +01:00
add an example of SetContextErrorHandler
This commit is contained in:
parent
ae828d8db9
commit
3582427df6
|
@ -4,6 +4,7 @@ import (
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
|
|
||||||
"github.com/kataras/iris/v12"
|
"github.com/kataras/iris/v12"
|
||||||
|
"github.com/kataras/iris/v12/x/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
// User example struct for json and msgpack.
|
// User example struct for json and msgpack.
|
||||||
|
@ -29,15 +30,16 @@ type ExampleYAML struct {
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
app := iris.New()
|
app := iris.New()
|
||||||
|
// Optionally, set a custom handler for JSON, JSONP, Protobuf, MsgPack, YAML, Markdown...
|
||||||
|
// write errors.
|
||||||
|
app.SetContextErrorHandler(new(errorHandler))
|
||||||
// Read
|
// Read
|
||||||
app.Post("/decode", func(ctx iris.Context) {
|
app.Post("/decode", func(ctx iris.Context) {
|
||||||
// Read https://github.com/kataras/iris/blob/master/_examples/request-body/read-json/main.go as well.
|
// Read https://github.com/kataras/iris/blob/master/_examples/request-body/read-json/main.go as well.
|
||||||
var user User
|
var user User
|
||||||
err := ctx.ReadJSON(&user)
|
err := ctx.ReadJSON(&user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.StatusCode(iris.StatusBadRequest)
|
errors.InvalidArgument.Details(ctx, "unable to parse body", err.Error())
|
||||||
ctx.Writef("unable to read body: %s\nbody is empty: %v", err.Error(), iris.IsErrEmptyJSON(err))
|
|
||||||
return
|
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.
|
// if passed to the `Run` then it will not print its passed error as an actual server error.
|
||||||
app.Listen(":8080", iris.WithOptimizations)
|
app.Listen(":8080", iris.WithOptimizations)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type errorHandler struct{}
|
||||||
|
|
||||||
|
func (h *errorHandler) HandleContextError(ctx iris.Context, err error) {
|
||||||
|
errors.Internal.Err(ctx, err)
|
||||||
|
}
|
||||||
|
|
|
@ -3966,9 +3966,9 @@ func WriteJSON(ctx stdContext.Context, writer io.Writer, v interface{}, options
|
||||||
}
|
}
|
||||||
|
|
||||||
// See https://golang.org/src/strings/builder.go#L45
|
// See https://golang.org/src/strings/builder.go#L45
|
||||||
func bytesToString(b []byte) string {
|
// func bytesToString(b []byte) string {
|
||||||
return *(*string)(unsafe.Pointer(&b))
|
// return *(*string)(unsafe.Pointer(&b))
|
||||||
}
|
// }
|
||||||
|
|
||||||
func stringToBytes(s string) []byte {
|
func stringToBytes(s string) []byte {
|
||||||
return *(*[]byte)(unsafe.Pointer(&s))
|
return *(*[]byte)(unsafe.Pointer(&s))
|
||||||
|
|
Loading…
Reference in New Issue
Block a user