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

Incorrect nullable enum deserialization behavior #1441

Open
iXamDev opened this issue Aug 7, 2024 · 0 comments
Open

Incorrect nullable enum deserialization behavior #1441

iXamDev opened this issue Aug 7, 2024 · 0 comments

Comments

@iXamDev
Copy link

iXamDev commented Aug 7, 2024

Hello, recently we encountered incorrect behavior of parsing nullable enumeration by json_annotation generated code.

I guess you should return null in $enumDecodeNullable function in enum_helper instead of ArgumentError() when the unknownValue is null. Since this is a nullable enum case and it should be null as a fallback value.

  if (unknownValue == null) {
    throw ArgumentError( // here
      '`$source` is not one of the supported values: '
      '${enumValues.values.join(', ')}',
    );
  }

In our case we have different API versions and there are cases when API uses unsupported enum values, and this is expected from the mobile app perspective, so the value is defined as nullable enum in the model in our mobile app. But with your implementation the app crashes if the mapping fails.

Ex.:

@JsonSerializable()
class Dto {
  @JsonKey(name: 'FeatureVersion')
  final FeatureVersion? featureVersion;
}

enum FeatureVersion {
  @JsonValue(1)
  first,
  @JsonValue(2)
  second,
  @JsonValue(3)
  third,
}

There is a workaround to handle that case by setting unknownEnumValue: JsonKey.nullForUndefinedEnumValue in the @JsonKey annotation but I guess it is redundant for nullable enums any way.

As a general concern I would suggest to introduce a special type exception for invalid enum mapping, for example for non nullable enums (function $enumDecode) and avoid using ArgumentError. Since it's not expected to catch errors in dart code, but the API contract mismatch is a common situation so it should be represented by exception to be able to be catched and handled.

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

1 participant