go runtime_error ai_generated true

panic:proto:Marshal 调用时传入 nil

panic: proto: Marshal called with nil

ID: go/proto-nil-message-fields

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

版本兼容性

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

根因分析

调用 proto.Marshal 时传入了 nil 的 *Message 指针。当未初始化的消息字段或 nil 响应直接传给 Marshal 时发生。

English

proto.Marshal was called with a nil *Message pointer. This happens when an uninitialized message field or a nil response is passed directly to Marshal.

generic

解决方案

  1. 95% 成功率
    Guard against nil before marshalling:
    if msg == nil {
        return nil, status.Error(codes.Internal, "nil message")
    }
    b, err := proto.Marshal(msg)
    if err != nil { return nil, err }
  2. 90% 成功率
    Initialize nested message fields with proto message constructors instead of leaving them nil:
    resp := &pb.Response{Data: &pb.Data{}} // not just &pb.Response{}

无效尝试

常见但无效的做法:

  1. 85% 失败

    The nil message indicates a logic bug; swallowing the panic leaves a corrupt state and the message is never sent, causing silent data loss.

  2. 75% 失败

    Marshalling an empty struct produces an empty byte slice, which downstream code interprets as a valid but empty message, corrupting semantics.