go runtime_error ai_generated true

panic: proto: Marshal called with nil

ID: go/proto-marshal-nil-message

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-05-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/protobuf 1.28+ active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 90% fail

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