hertz icon indicating copy to clipboard operation
hertz copied to clipboard

Question: How to catch internal error

Open BeanWei opened this issue 1 year ago • 2 comments

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=

BeanWei avatar Sep 19 '22 08:09 BeanWei

hello @BeanWei

  • you can refer to https://www.cloudwego.io/zh/docs/hertz/reference/config/ and use WithMaxRequestBodySize

li-jin-gou avatar Sep 19 '22 09:09 li-jin-gou

The error limiting the body size is executed before the biz handler is executed, so you don't get the error.

li-jin-gou avatar Sep 19 '22 09:09 li-jin-gou