I have a code that gets data from the user and validates rather it's valid or not.
The validation is for the data from the URL
and the data from the JSON
.
The problem is that in case of URL
the path field contains arg0
and that it requires me to take it from the message
:
@ValidId (message = "The field is invalid")
private Long field;
annotation of the field.
In case of JSON
, I simply can get the field from the path.substring(path.lastIndexOf('.') + 1)
.
i.e.
protected String buildErrorMessage(ConstraintViolation<?> violation) {
String path = violation.getPropertyPath().toString();
String field = path.substring(path.lastIndexOf('.') + 1);
//field = `arg0` in case of url
//field = `field` in case of JSON
}
If I'm facing a ConstraintViolation -
how can I find out if the violation is from JSON
or GET
?
EDIT
This is where I call the buildErrorMessage from -
public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> {
@Override
public Response toResponse(ValidationException exception) {
if (exception instanceof ConstraintViolationException) {
final ConstraintViolationException constraint = (ConstraintViolationException) exception;
for (final ConstraintViolation<?> violation : constraint.getConstraintViolations()) {
String message = buildErrorMessage(violation); //HERE
}
}
Here are some steps that can be helpful when implementing an ExceptionMapper
to check whether the ConstraintViolation
is related to an invalid parameter sent in the URL or related to an invalid property sent in the JSON payload:
Path
from the ConstraintViolation
using the getPropertyPath()
method;Node
from the property Path
;Node
kind using the getKind()
method.Bear in mind that parameter annotations such as @QueryParam
, @PathParam
and @MatrixParam
can be placed in method parameter, resource class field, or resource class bean property.
I would recommend you to look at my implementation of ExceptionMapper
for ConstraintViolationException
available in GitHub.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With