Reputation: 134
I am using Jersey (JAX-RS) and I'm trying to implement a validation. I have a problem with a response returned by my application when a validation error occurs. Now the response looks like this:
[{
"message": "Custom message",
"messageTemplate": "{custom.message.template}",
"path": "SomeJerseyResource.resourceMethod.arg0.names[0]",
"invalidValue":"[value1, value2]"
}]
where "SomeJerseyResourceClass.resourceMethod" is a JAX-RS resource:
public class SomeJerseyResource {
@POST
@Path("/path")
public Response resourceMethod(@Valid RequestModel request) {
/** method body **/
}
}
and validation constraint is assigned to a getter in RequestModel:
public class RequestModel {
private List<String> names = new ArrayList<>();
@MyConstraint
public List<String> getNames() {
return tags;
}
}
I have a custom ConstraintValidator, where I validate each element of that List.
Problem
SomeJerseyResource.resourceMethod.arg0.names[0]
I want arg0.names[0]
only. Client doesn't know about server classes and methods, and he wouldn't be able to properly assign errors to fields when he receives response like that.I didn't find any easy way to do that. Do you have any ideas?
Upvotes: 3
Views: 1487
Reputation: 208964
You can just write an ExceptionMapper<ConstraintViolationException>
to return the Response
of your liking. Jersey uses an ExceptionMapper<ViolationException>
. ConstraintViolationException
extends from ViolationException
, so you're mapper is more specific, and would take precedence in the choosing of the mapper. Jersey's mapper, returns the response as a ValidationError
, that's why the body is how it is. But you can make it whatever you want.
If you just want the invalidValue
list, then just iterate through the ConstraintViolation
s from ContraintViolationException.getConstraintViolations()
, and get the invalidValue
from the ConstraintViolation
.
Upvotes: 3