go runtime_error ai_generated true

proto: Marshal 被调用时传入了 nil 消息

proto: Marshal called with nil message

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 95% 成功率
    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% 成功率
    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
    }

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 70% 失败

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