kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Catching exceptions from the constructor when deserialization for clearer error info

Open Stream29 opened this issue 1 month ago • 2 comments

What is your use-case and why do you need this feature?

I'm trying to migrate my Python AI agent project into Kotlin.

With Python

When validating the json output from the LLM, I use Pydantic to set the requirements on the fields of a data class. It gives me clear error message with a unified ValidationError, allowing me to extract error information and fix it with LLM.

With Kotlin

kotlinx.serialization gives clear error message with path when there is missing fields. When it comes with the validation of the value, I use a init block in the data class to validate the input value. When the validation fails, the exception is thrown with no path info, and it's not wrapped with SerializationException.

Describe the solution you'd like

When the constructor throws an IllegalArgumentException while deserialization, the exception should be wrapped and add path info on it. When the exception happend, the raw input should be kept and accessible fully. (Currently the input will be shorten if larger than 200 chars)

Stream29 avatar Nov 13 '25 15:11 Stream29

Related: #2165

On a side note: the raw input should be kept and accessible fully. is likely unfeasible because inputs may be large and cause memory leaks

sandwwraith avatar Nov 24 '25 13:11 sandwwraith

One thing that would make sense is to support is to allow (possibly wrapped) exceptions that hold information on the location of the exception (line number, column number or byte number). Then, if available (strings), the context could be reconstructed.

pdvrieze avatar Nov 24 '25 19:11 pdvrieze