hertz
hertz copied to clipboard
Question: How to catch internal error
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)
// Cannot catch `engine.go:410: [Error] HERTZ: Error=body size exceeds the given limit, remoteAddr=`
func CatchOverBodySize() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
hlog.Info("pre")
c.Next(ctx)
hlog.Info("after")
hlog.Info(c.Errors)
if err := c.Errors.Last(); err != nil {
hlog.Error(err)
}
}
}
func main() {
h := server.Default(server.WithHostPorts("127.0.0.1:8080"))
h.Use(CatchOverBodySize()) // cannot catch
h.POST("/upload", func(ctx context.Context, c *app.RequestContext) {
c.JSON(consts.StatusOK, utils.H{})
})
h.Spin()
}
Step: Upload a large file, will throw body size exceeds the given limit
error.
How to catch engine.go:410: [Error] HERTZ: Error=body size exceeds the given limit, remoteAddr=
hello @BeanWei
- you can refer to https://www.cloudwego.io/zh/docs/hertz/reference/config/ and use
WithMaxRequestBodySize
The error limiting the body size is executed before the biz handler is executed, so you don't get the error.