自定义中间件

参考官方文档实现自定义中间件
https://www.cloudwego.io/zh/docs/hertz/tutorials/basic-feature/middleware/

package middleware

import (
    "HertzDemo/internal/pkg"
    "context"

    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/common/hlog"
)

func GlobalErrorHandler() app.HandlerFunc {
    return func(ctx context.Context, c *app.RequestContext) {
        // pre-handler
        hlog.Info("全局异常处理:前置处理~~~~~~~~~~")
        c.Next(ctx)
        // post-handle
        hlog.Info("全局异常处理:后置处理~~~~~~~~~~")
        if len(c.Errors) == 0 {
            return
        }
        pkg.ErrWithMessage(c, c.Errors.Last().Error())
    }
}

注册中间件

main方法中增加注册上面自定义的中间件

h.Use(middleware.GlobalErrorHandler())

应用

举例参数校验发生错误时全局异常处理

package handler

import (
    "HertzDemo/internal/genSql/handler/req"
    "HertzDemo/internal/genSql/service"
    "HertzDemo/internal/pkg"
    "context"
    "fmt"

    vd "github.com/bytedance/go-tagexpr/v2/validator"
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/common/errors"
    "github.com/cloudwego/hertz/pkg/common/hlog"
)

func InsertResource(ctx context.Context, c *app.RequestContext) {
    var req req.InsertReq
    if err := c.BindAndValidate(&req); err != nil {
        hlog.Error("新增资源解析参数错误!")
        //存储错误到RequestContext中
        c.Error(errors.NewPublic("新增资源解析参数错误!"))
        return
    }
    fmt.Println(vd.Validate(req))
    hlog.Infof("请求参数:%s", req)
    pkg.Ok(c, service.InsertResource(req))
}
文章目录