falouu
falouu

Reputation: 134

Jersey, JSR 303 validation - custom "path" and "invalidValue" in ValidationError

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

I didn't find any easy way to do that. Do you have any ideas?

Upvotes: 3

Views: 1487

Answers (1)

Paul Samsotha
Paul Samsotha

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 ConstraintViolations from ContraintViolationException.getConstraintViolations(), and get the invalidValue from the ConstraintViolation.

Upvotes: 3

Related Questions