Kotlin / kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Apache License 2.0
5.41k stars 620 forks source link

How the deserialization failures are supposed to be catched? #2805

Open unclechu opened 2 months ago

unclechu commented 2 months ago

I’m trying to catch a deserialization error (from a call like this: Json.decodeFromString<Foo>("...")) and transform it into a pure value (e.g. Either<JsonDeserializationFailure, Foo>). But I couldn’t find a solution, I don’t want to catch a wide-scoped Exception that can be totally not related to deserialization issue. I see that the library throws kotlinx.serialization.json.internal.JsonDecodingException but I can’t access it because it’s internal. How is it supposed to be done?

I went through a bunch of articles about kotlinx.serialization but apparently none of them are talking about errors handling which leaves me confused.

unclechu commented 2 months ago

I wonder why does the kotlinx.serialization.json.internal.JsonDecodingException has to be internal and not a publicly exposed one?

sandwwraith commented 2 months ago

decodeFromString documentation (https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/decode-from-string.html) mentions that this method can throw kotlinx.serialization.SerializationException in case of decoding errors and IllegalArgumentException in case of data validation errors (e.g. require(...) in init {} block of the class). Does that answer your question?

pdvrieze commented 2 months ago

@sandwwraith Just note that require throws IllegalArgumentException (check throws IllegalStateException). In this case require/IllegalArgumentException would be the appropriate exceptions as it is "input" validation.

sandwwraith commented 2 months ago

Yeah, I mixed them up in my comment, documentation clearly mentions IllegalArgument.