go runtime_error ai_generated true

panic:proto:Marshal 被以 nil 调用

panic: proto: Marshal called with nil

ID: go/proto-nil-message-marshal

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率
    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% 成功率
    Add a unit test that asserts every handler returns either a non-nil message or a non-nil error.

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 70% 失败

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