5

I am developing a simple RESTFul service using JBoss-7.1 and RESTEasy. I have a REST Service, called CustomerService as follows:

@Path(value="/customers")
@ValidateRequest
class CustomerService
{
  @Path(value="/{id}")
  @GET
  @Produces(MediaType.APPLICATION_XML)
  public Customer getCustomer(@PathParam("id") @Min(value=1) Integer id) 
  {
    Customer customer = null;
    try {
        customer = dao.getCustomer(id);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return customer;
    }
}

Here when I hit the url http://localhost:8080/SomeApp/customers/-1 then @Min constraint will fail and showing the stacktrace on the screen.

Is there a way to catch these validation errors so that I can prepare an xml response with proper error message and show to user?

K. Siva Prasad Reddy
  • 11,786
  • 12
  • 68
  • 95

1 Answers1

10

You should use exception mapper. Example:

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<javax.validation.ConstraintViolationException> {

    public Response toResponse(javax.validation.ConstraintViolationException cex) {
       Error error = new Error();
       error.setMessage("Whatever message you want to send to user. " + cex);
       return Response.entity(error).status(400).build(); //400 - bad request seems to be good choice
    }
}

where Error could be something like:

@XmlRootElement
public class Error{
   private String message;
   //getter and setter for message field
}

Then you'll get error message wrapped into XML.

Piotr Kochański
  • 21,862
  • 7
  • 70
  • 77
  • hi siva, how did you convert meaningful error object out of cex.getConstraintViolations() which returns Set> , how do you identify T generic type here ? – Rakesh Waghela Jul 11 '13 at 14:13
  • 1
    This is not working for me with Wildfly 8.2.0 (HV 5.1.3, RestEasy 3.0.10), the ExceptionMapper is being completely ignored (the exception mapper is never called, the entity in the response is not of the type I'm setting, I'm getting a ProcessingException because of the mismatch). Other exception mappers work flawlessly. What you you think could be the cause? – jpangamarca Oct 27 '15 at 05:44
  • @jpangamarca: RestEasy 3.0.10 does not throw the ConstraingViolationException but its own ResteasyViolationException. Your ValidationExceptionMapper should handle this exception. (this should be fixed in RestEasy 3.0.12). See https://issues.jboss.org/browse/RESTEASY-1137 – robotniko Jun 16 '16 at 12:34
  • Can we do this? Subclass ConstraintViolationException. Throw an instance of the subclass depending on the bean/error, and catch the exception in ExceptionMapper ? Possibly have a unique ExceptionMapper for a given subclass – KiranCK Oct 18 '16 at 15:30
  • 1
    This is wrong. Please refer to https://stackoverflow.com/questions/44308101/customizing-jax-rs-response-when-a-constraintviolationexception-is-thrown-by-bea – Yuantao Dec 08 '17 at 18:40