Skip to content

[Java] new option: Throw an exception for invalid enum values instead of using null #625

@jmini

Description

@jmini

I have a similar problem than the one reported in swagger-api/swagger-codegen#5950

When working with enum in a java server, if the enum value sent by the client is unknown, after deserialization, the value is set to null.

This might be useful in some cases (the OpenAPI Spec does not always contains all the possible values) but is not the behavior expected in most of the cases.


After having looked at the thread swagger-api/swagger-codegen#5950
I propose to add a new option: useNullForUnknownEnumValue:

  • true (current behavior 3.1.x)
  • false

In my opinion (and as other participants in the original thread) starting with 3.2.0 the new default should be false.

With useNullForUnknownEnumValue == true:

@JsonCreator
public static EnumStringEnum fromValue(String text) {
for (EnumStringEnum b : EnumStringEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}

With useNullForUnknownEnumValue == false:

   @JsonCreator 
   public static EnumStringEnum fromValue(String text) { 
     for (EnumStringEnum b : EnumStringEnum.values()) { 
       if (String.valueOf(b.value).equals(text)) { 
         return b; 
       } 
     } 
     throw new IllegalArgumentException("Unexpected value '" + text + "'");
   } 
} 

In the thread there is also a discussion about removing fromValue and the @JsonCreator to let Jackson handling deserialisation.

This is not possible in my opinion:

  • There are cases where the Java enum name is not the enum value. (Lowercase/uppercase, values with spaces are allowed in OAS3, …)
  • The type of the value is not always a string.

cc: @TehBakker, @slarti-b, @wing328, @cbornet

Java Technical Committee: @bbdouglas (2017/07) @JFCote (2017/08) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions