The ConstraintViolation has path and message, which is sufficient for most cases.
But it is not the most straightforward design if I need to pinpoint on the exact constraint being violated and act on it. For instance, to pick out a particular constraint violation and throw an alternate Exception instead of the generic Exception.
Currently, to workaround this limitation, there are possibly two ways:
- Override the
path using the withPath { absolute("some_identifier") } DSL
- Override the
message using the otherwise { "some_identifier" } DSL
The first workaround loses the path in a meaningful way. And the second workaround loses human readable messages.
Is it possible to add a third field of metadata: Map<String, Any> to ConstraintViolation, so that user can freely attach whatever metadata they need to the violation instance.
Possible DSL design:
val validate = Validator<Data> {
fieldOne.apply {
shouldNotBeEmpty()
constraint { it.meetsCustomCondition() } withMetadata { mapOf("key" to "customErrorKey1") }
}
}
Then, when analyzing the ConstraintViolation:
fun handleViolation(cv: ConstraintViolation) {
if (cv.metadata["key"] == "customErrorKey1")
throw CustomError(cv.message)
throw FallbackError(cv.message)
}
The
ConstraintViolationhaspathandmessage, which is sufficient for most cases.But it is not the most straightforward design if I need to pinpoint on the exact constraint being violated and act on it. For instance, to pick out a particular constraint violation and throw an alternate Exception instead of the generic Exception.
Currently, to workaround this limitation, there are possibly two ways:
pathusing thewithPath { absolute("some_identifier") }DSLmessageusing theotherwise { "some_identifier" }DSLThe first workaround loses the
pathin a meaningful way. And the second workaround loses human readable messages.Is it possible to add a third field of
metadata: Map<String, Any>toConstraintViolation, so that user can freely attach whatever metadata they need to the violation instance.Possible DSL design:
Then, when analyzing the
ConstraintViolation: