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

Fix MissingFieldException duplication #2213

Merged
merged 2 commits into from
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package kotlinx.serialization.json

import kotlinx.serialization.*
import kotlinx.serialization.json.Json.Default.decodeFromString
import org.junit.*
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.PrintWriter
import java.io.StringWriter
import kotlin.test.*

class MissingFieldExceptionWithPathTest {

@Test // Repro for #2212
fun testMfeIsNotReappliedMultipleTimes() {
val inputMalformed = """{"title": "...","cast": [{}]"""
try {
Json.decodeFromString<Movie>(inputMalformed)
fail("Unreacheable state")
} catch (e: MissingFieldException) {
val fullStackTrace = e.stackTraceToString()
val i1 = fullStackTrace.toString().indexOf("at path")
val i2 = fullStackTrace.toString().lastIndexOf("at path")
assertEquals(i1, i2)
assertTrue(i1 != -1)
}
}

@Serializable
data class Movie(
val title: String,
val cast: List<Cast>,
)

@Serializable
data class Cast(
val name: String
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ internal open class StreamingJsonDecoder(
return result

} catch (e: MissingFieldException) {
// Add "at path" if and only if we've just caught an exception and it hasn't been augmented yet
if (e.message!!.contains("at path")) throw e
// NB: we could've use some additional flag marker or augment the stacktrace, but it seemed to be as too much of a burden
throw MissingFieldException(e.missingFields, e.message + " at path: " + lexer.path.getPath(), e)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer val mfe = .. new mfe with better message ... to later do mfe.stackTrace = e.stackTrace, but unfortunately, it works only on JVM, not sure if we should bother

shanshin marked this conversation as resolved.
Show resolved Hide resolved
}
}
Expand Down