go runtime_error ai_generated true

proto: Marshal called with nil message

ID: go/protobuf-proto-marshal-nil-message

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/protobuf 1.28+ active

Root Cause

A nil protobuf message pointer was passed to proto.Marshal or protojson.Marshal, typically from a handler that returned a nil pointer on error paths without checking.

generic

中文

向 proto.Marshal 或 protojson.Marshal 传入了 nil 的 protobuf 消息指针,通常源自处理器在错误路径返回 nil 指针而未做检查。

Workarounds

  1. 95% success
    if msg == nil {
        return nil, status.Error(codes.Internal, "nil message")
    }
    b, err := proto.Marshal(msg)
    if err != nil { return nil, status.Error(codes.Internal, err.Error()) }
  2. 90% success
    func (s *srv) Get(ctx context.Context, req *pb.GetReq) (*pb.GetResp, error) {
        if req == nil { return &pb.GetResp{}, nil }
        return &pb.GetResp{Id: req.Id}, nil
    }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Swallowing the panic leaves the caller with no message and no error, causing silent data loss downstream.

  2. 70% fail

    Changes wire semantics; clients expecting a specific message type get an unrelated type and may fail to unmarshal.