middleware.go 888 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
package server

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"grpc-base/common/logger"
	"grpc-base/service/testuser/api"
	"runtime/debug"
)

// 捕获异常
func recoverHandler(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	defer func() {
		if err2 := recover(); err2 != nil {
			logger.Errorf("触发panic, recover: %v\n%s\n", err2, debug.Stack())
			err = status.Errorf(codes.Internal, "触发panic: %v", err2)
		}
	}()
	return handler(ctx, req)
}

// 记录请求信息
func logBeforeReq(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	if v, ok := req.(*api.UserInfoReq); ok {
		logger.Debugf("request: %s data: %v\n", info.FullMethod, v)
	}
	return handler(ctx, req)
}