go runtime_error ai_generated true

panic:proto:以 nil 调用 Marshal

panic: proto: Marshal called with nil

ID: go/proto-marshal-nil-message

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-05-02首次发现

版本兼容性

版本状态引入弃用备注
google.golang.org/protobuf 1.28+ active

根因分析

以 nil 的 proto.Message 调用 google.golang.org/protobuf 的 Marshal/Unmarshal,通常是本应构建请求的函数返回了 nil 指针。

English

google.golang.org/protobuf Marshal/Unmarshal was called with a nil proto.Message, typically a nil pointer returned from a function that was supposed to build a request.

generic

解决方案

  1. 95% 成功率
    Guard against nil before marshaling:
    if req == nil {
        return status.Error(codes.InvalidArgument, "request is nil")
    }
    _ = req.ProtoReflect().IsValid()
  2. 90% 成功率
    Return value types instead of pointers from builders, or always allocate:
    req := &pb.GetUserRequest{}
    if userID != "" { req.Id = userID }

无效尝试

常见但无效的做法:

  1. 80% 失败

    Recovering hides the nil bug; the request is still malformed and downstream calls fail silently.

  2. 90% 失败

    proto.Clone(nil) also panics with the same message.