Let’s imagine I have the following classes:
data class MyClass1(
val someField1: String,
val myClass2: MyClass2?,
)
data class MyClass2(
val someField2: String,
val someField3: String?,
)
And also I have some RestController
@PostMapping("/test")
fun test(
@RequestBody request: MyClass1,
) {
// do smth
}
I want to check the request param for any violations of nullability restrictions among its properties, collect all of these violations into a single list and throw an exception if this list is not empty.
The obvious problem is that kotlin throws its own exception automatically if notices null value for any non-nullable property. So there is no chance to collect all of these violations per request into a single exception at once.
The solutions I’ve tried:
- An attempt to collect these violations inside of custom Deserializer and throw exception, but there is a problem with cycling deserialization of correct cases(deserializer -> object mapper -> deserializer -> …)
- Turn all properties in mentioned before classes
MyClass1
andMyClass2
into nullable. Kotlin will always parse them without exceptions and so later I can check props by myself via reflection and custom annotations. The problem is that I cannot modify library classes and make props inside of them nullable. - Create dublicate classes for both
MyClass1
andMyClass2
with nullable props, use them inside of controller, check for null violations and then, if all things are ok, convert them into original classes.
Are there any better options for this case?