Hi, I've got a question: If I create a custom seri...
# serialization
k
Hi, I've got a question: If I create a custom serializer, how do I get the name of the field being deserialized ($FIELD_NAME)?
Copy code
override fun deserialize(decoder: Decoder): NonEmptyString {
        val decodedValue = decoder.decodeString()
        when (val result = NonEmptyString.of(decodedValue)) {
            is Success -> return result.value
            is Failure -> throw SerializationException(
                "Unable to deserialize '$decodedValue' of $FIELD_NAME into ${descriptor.serialName}: ${result.error.message}"
            )
        }
    }
I need to see the context in the exception because there are many feilds of type NonEmptyString in the json document being deserialized
d
Not possible to get it at this layer of abstraction. There's also the chance that there's no field and this is a top level serialization.
k
so what is the correct way to propagate the error and catch the exception with the context info?
d
No idea
k
That sux.. such a basic thing I would expect from json serialization library and I cannot figure it out already for a whole afternoon of googling and doing some hopeless experiments 😕
c
can’t you just look at the stacktrace of the exception that you throw to find a good place to catch it where the field name is known?
k
No, it is somewhere deep in the library and I don't know how to intercept it and if I were to dig in it, it would be probably faster to write my own library from scratch
Copy code
kotlinx.serialization.SerializationException: Unable to deserialize NonEmptyString from '': Provided string value cannot be empty
	at com.example.someapp.model.generic.NonEmptyStringSerializer.deserialize(GenericTypes.kt:48)
	at com.example.someapp.model.generic.NonEmptyStringSerializer.deserialize(GenericTypes.kt:38)
	at kotlinx.serialization.json.internal.PolymorphicKt.decodeSerializableValuePolymorphic(Polymorphic.kt:63)
	at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeSerializableValue(StreamingJsonDecoder.kt:32)
	at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:43)
	at kotlinx.serialization.encoding.AbstractDecoder.decodeNullableSerializableElement(AbstractDecoder.kt:79)
	at com.example.someapp.model.SomeDomainObject$$serializer.deserialize(Domain.kt:56)
	at com.example.someapp.model.SomeDomainObject$$serializer.deserialize(Domain.kt:56)
	at kotlinx.serialization.json.internal.PolymorphicKt.decodeSerializableValuePolymorphic(Polymorphic.kt:63)
	at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeSerializableValue(StreamingJsonDecoder.kt:32)
	at kotlinx.serialization.json.Json.decodeFromString(Json.kt:85)
    at com.example.someapp.function.request.ParsePayloadFunction.invoke-Ngtr28s(ParsePayloadFunction.kt:17)