Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling Unknown Enum Values #1073

Closed
FutureSeller opened this issue Feb 23, 2025 · 1 comment
Closed

Handling Unknown Enum Values #1073

FutureSeller opened this issue Feb 23, 2025 · 1 comment

Comments

@FutureSeller
Copy link

FutureSeller commented Feb 23, 2025

Greetings!

In enumToJsonInternal function, it appears that when an unknown value is encountered, the integer value is passed through as is.

function enumToJsonInternal(
  desc: DescEnum,
  value: unknown,
  enumAsInteger: boolean,
): string | number | null {
  if (typeof value != "number") {
    throw new Error(
      `cannot encode ${desc} to JSON: expected number, got ${formatVal(value)}`,
    );
  }
  if (desc.typeName == "google.protobuf.NullValue") {
    return null;
  }
  if (enumAsInteger) {
    return value; // << [[ here ]]
  }
  const val = desc.value[value] as DescEnumValue | undefined;
  return val?.name ?? value; // if we don't know the enum value, just return the number << [[ here ]]
}

According to protobuf buffers document, the default value for an enum can be used 0. How about adding an option to specify a default value for unknown enum values, or converting them to 0?

Thanks!

@timostamm
Copy link
Member

Hey Jihoon,

in proto3, enums are open, which means you can assign values that are not defined in the enum.

For example:

syntax="proto3";

enum Foo {
  FOO_UNSPECIFIED = 0;
  FOO_A = 1;
}

message Example {
  Foo foo = 1;
}

Creating an instance of the message Example, and assigning the value 2 to the field foo is not an error. Serializing the message to JSON should yield {"foo": 2}, and parsing this JSON should yield a message with foo = 2.

This can be unexpected, but we cannot change this behavior because it would not be compatible with other Protobuf implementations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants