Skip to content

[BUG] [kotlin-spring] enum forValue should throw IllegalArgumentException #21621

@swurzinger

Description

@swurzinger

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

For any enum class the generator creates a forValue helper method, which looks up an enum value for a given string value. In case it can't find an according enum value it throws a NoSuchElementException. However, it should throw a IllegalArgumentException, as does the valueOf() method in Java/Kotlin (see https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#valueOf-java.lang.Class-java.lang.String- or https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants). The wrong Exception type causes e.g. issues with Jackson (the method is annotated with @JsonCreator), as it expects a IllegalArgumentException in case the string value is not a valid enum value.

openapi-generator version

4.17, but previous versions are affected too

OpenAPI declaration file content or url

any enum, e.g.:

components:
  schemas:
    MyEnum:
      type: string
      enum:
        - VALUE_A
        - VALUE_B
        - VALUE_C
Generation Details

generatorName: kotlin-spring

e.g. https://github.com/OpenAPITools/openapi-generator/blob/master/bin/configs/kotlin-spring-boot-3.yaml

Steps to reproduce

call MyEnum.forValue("invalid") with an invalid string value. It should throw a IllegalArgumentException, but throws a NoSuchElementException currently.

Related issues/PRs

none

Suggest a fix
fun forValue(value: {{dataType}}): {{classname}} {
    return values().firstOrNull{it -> it.value == value}
        ?: throw IllegalArgumentException("Unexpected value '$value' for enum '{{classname}}'")
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions