Home > database >  javax.validation.constraints.NotNull not work for java.time.Instant in Kotlin
javax.validation.constraints.NotNull not work for java.time.Instant in Kotlin

Time:08-25

Constraint @NotNull doesn't work for field instance of Instant after migration from java to kotlin. I mean that in java because of this constraint I got 422 in case of updatedAt was null but in kotlin I have 400. Could you give me some clues why is that and how I can resolve it?

data class User(
@NotNull
val updatedAt: Instant
)

CodePudding user response:

Since your updatedAt property is defined to be of non-nullable type Instant, it is not possible that it is null, and thus, it is not possible that the @NotNull constraint fails. Before it can fail, there will probably be an IllegalArgumentException when some mechanism tries to set the property to null.

That IllegalArgumentException in turn is then probably translated by some exception handler into a Rest code of 400, while whatever exception that would be thrown by checking a violation of the constraint would be translated into a Rest code of 422.

You should try to make the property nullable in order to allow the property to become null which can then be checked to violate the @NotNull constraint:

data class User(
   @NotNull
   val updatedAt: Instant?
)

Alternatively, you could try to catch the exception that is thrown when setting the value of updatedAt and replace it. Or, you could write an exception handler that returns Rest code 422 instead of 400. But since I do not know much about your technology stack, I cannot give you more details on that.

  • Related