feat 错误包装

This commit is contained in:
2026-01-16 22:13:08 +08:00
parent ed80af6ae2
commit 6d5c7e81e9
5 changed files with 17 additions and 7 deletions

View File

@@ -17,7 +17,7 @@ func (s *Server) ToClient(server grpc_pb.Gateway_ToClientServer) error {
defer wg.Done()
defer func() {
if err := recover(); err != nil {
log.Errorf("Action panic: %v", err)
log.Errorf("ToClient panic: %v", err)
}
}()
for {

View File

@@ -16,8 +16,9 @@ type Server struct {
func NewServer(ttl int64) *Server {
s := &Server{
Base: service.Base{
Target: common.KeyDiscoverGateway,
EtcdTTL: ttl,
Target: common.KeyDiscoverGateway,
ServiceName: common.KeyDiscoverServiceNameGateway,
EtcdTTL: ttl,
},
}
s.Base.OnInit = s.OnInit

View File

@@ -28,9 +28,11 @@ func ginLogger(logger *zap.SugaredLogger) gin.HandlerFunc {
path := c.Request.URL.Path
c.Next()
cost := time.Since(start)
usn, _ := c.Get("usn")
logger.Infof(fmt.Sprintf(
"HTTP Method:%v Code:%v Time:%v IP:%v Path:%v",
"[usn:%v] Method:%v Code:%v Time:%v IP:%v Path:%v",
usn,
c.Request.Method,
c.Writer.Status(),
cost,
@@ -45,6 +47,7 @@ func authJwt() gin.HandlerFunc {
pList := strings.SplitN(c.Request.URL.Path, "/", 4)
if len(pList) < 4 || pList[2] == "" {
http_resp.JsonNotFound(c)
c.Abort()
return
}
// 如果是Public接口有Token就读没有就算了
@@ -69,6 +72,8 @@ func authJwt() gin.HandlerFunc {
// 这里将Header写到请求中grpc-gateway框架会读取然后传给grpc服务
c.Request.Header.Set("X-Usn", claims.USN)
// 这里写到上下文中,打日志
c.Set("usn", claims.USN)
c.Next()
}
}

View File

@@ -2,6 +2,7 @@ package http_gateway
import (
"context"
"git.hlsq.asia/mmorpg/service-common/discover/common"
"git.hlsq.asia/mmorpg/service-common/log"
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp"
@@ -11,6 +12,7 @@ import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"google.golang.org/protobuf/encoding/protojson"
)
@@ -47,6 +49,7 @@ func InitRouter() *gin.Engine {
gin.Recovery(),
ginLogger(log.GetLogger().Named("GIN")),
cors.New(corsConfig()),
otelgin.Middleware(common.KeyDiscoverServiceNameGateway),
)
r.HandleMethodNotAllowed = true

View File

@@ -33,11 +33,12 @@ func ErrorHandler(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w
code = http_resp.Failed.Code()
msg = http_resp.Failed.Error()
}
if st.Code() == codes.Unknown ||
st.Code() == codes.Unimplemented ||
st.Code() == codes.NotFound {
if st.Code() == codes.Unknown || st.Code() == codes.Unimplemented || st.Code() == codes.NotFound {
msg = st.Message()
}
if st.Code() == codes.NotFound {
code = http_resp.NotFound.Code()
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(grpcCodeToHTTPCode(st.Code()))