InvalidProtocolBufferException data schema_error ai_generated true

Protobuf反序列化失败:读取包含新枚举值的数据时出现'未知枚举值'

Protobuf deserialization fails with 'Unknown enum value' when reading data with new enum values

ID: data/protobuf-unknown-enum-value

其他格式: JSON · Markdown 中文 · English
85%修复率
86%置信度
1证据数
2023-12-01首次发现

版本兼容性

版本状态引入弃用备注
Protocol Buffers 3.21+ active
protoc 24.0+ active
gRPC 1.60+ active

根因分析

Protobuf定义中添加了新的枚举值,但读取器的生成代码未更新,导致其拒绝未知值而非将其视为未识别字段。

English

A new enum value was added to a Protobuf definition, but the reader's generated code is not updated, causing it to reject the unknown value instead of treating it as an unrecognized field.

generic

官方文档

https://protobuf.dev/programming-guides/proto3/#enum

解决方案

  1. 更新读取器使用最新的.proto文件并重新生成代码。对于Java:使用更新后的定义运行`protoc --java_out=src/main/java myproto.proto`。
  2. 在.proto文件中使用`allow_alias`选项将新枚举值临时映射到现有值:`option allow_alias = true; NEW_VALUE = EXISTING_VALUE;`
  3. 将字段视为`google.protobuf.Int32Value`包装器以绕过枚举验证,然后在应用程序代码中将整数转换为适当的枚举。

无效尝试

常见但无效的做法:

  1. 100% 失败

    The reader still runs old code; regenerating without redeployment has no effect.

  2. 80% 失败

    Enums in proto3 are already implicitly optional; making them explicit does not change how unknown values are handled.

  3. 65% 失败

    Protobuf's generated code throws an exception during deserialization that cannot be easily caught without modifying the generated code itself.