go runtime_error ai_generated true

panic: proto: Marshal called with nil

ID: go/proto-nil-message-marshal

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/protobuf 1.31+ active — — —

Root Cause

proto.Marshal was passed a nil pointer, often from a handler returning (nil, nil) or an uninitialized nested field.

generic

中文

proto.Marshal 接收到 nil 指针,通常源于处理函数返回 (nil, nil) 或未初始化的嵌套字段。

Workarounds

  1. 95% success
    Always return a non-nil message or an explicit status error:
    if user == nil {
      return nil, status.Error(codes.NotFound, "user not found")
    }
    return &pb.GetUserResponse{User: user}, nil
  2. 90% success
    Add a unit test that asserts every handler returns either a non-nil message or a non-nil error.

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Masks the bug; nil responses keep leaking to clients as empty messages.

  2. 70% fail

    Changes the API contract; clients can no longer distinguish 'no result' from 'empty result'.