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

Misleading MissingFieldException on unexpected enum with coerceInputValues #2529

Closed
gmk57 opened this issue Dec 14, 2023 · 1 comment
Closed
Assignees
Labels

Comments

@gmk57
Copy link

gmk57 commented Dec 14, 2023

Describe the bug
Json configuration option coerceInputValues = true is very helpful to future-proof network code, but it has some unfortunate side effects. Some of them are already raised in different issues, but this one is not (AFAIK):

When model has enum field with no default, and unexpected enum value is encountered, confusing MissingFieldException is thrown instead of correct exception with helpful error message. This caught me off-guard a couple times, causing time wasted looking for typos in field name, etc.

To Reproduce

@Test
fun `GIVEN json with unexpected enum value WHEN deserialize THEN throw meaningful exception`() {
    val jsonWithUnexpectedValue = """
        {
            "color": "SOMETHING_UNEXPECTED"
        }
    """.trimIndent()
    val jsonSerializer = Json {
        coerceInputValues = true
    }
    val throwable = runCatching {
        jsonSerializer.decodeFromString<Model>(jsonWithUnexpectedValue)
    }.exceptionOrNull()

    assertThat(throwable, instanceOf(SerializationException::class.java))
    assertThat(throwable!!.message, containsString("SOMETHING_UNEXPECTED"))
}

@Serializable
data class Model(val color: Color)

enum class Color { RED, GREEN }

Expected behavior
kotlinx.serialization.SerializationException: gmk57.Color does not contain element with name 'SOMETHING_UNEXPECTED' at path $.color
That's what is thrown with coerceInputValues = false

Observed behavior
kotlinx.serialization.MissingFieldException: Field 'color' is required for type with serial name 'gmk57.Model', but it was missing at path: $

Environment

  • Kotlin version: 1.9.10
  • Library version: 1.6.2

I guess the root cause is the same as in #1947, but the issue we face is a bit different.

@sandwwraith sandwwraith self-assigned this Dec 15, 2023
sandwwraith added a commit that referenced this issue Dec 15, 2023
…ault values

Trying so leads to confusing errors about missing values despite a json key actually
present in the input.

Fixes #2529
@gmk57
Copy link
Author

gmk57 commented Feb 17, 2024

Thanks for fixing it! 👍

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

No branches or pull requests

2 participants