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) }