Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch RESTEasy Bean Validation Errors?

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?

like image 816
K. Siva Prasad Reddy Avatar asked May 09 '12 12:05

K. Siva Prasad Reddy


People also ask

How does Hibernate Validator work?

Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming.

How does Java Bean validation work?

Java Bean Validation, also known as JSR-303 (Java Specification Requests), is an annotation based validation specification for validating fields on objects. Java Bean Validation uses flexible annotations, which can be overridden or extended through the Java code or in an XML file, to apply validation constraints.

What is Bean Validation API?

The Bean Validation API is introduced with the Java™ Enterprise Edition 6 platform as a standard mechanism to validate JavaBeans in all layers of an application, including presentation, business, and data access. Before the Bean Validation specification, JavaBeans were validated in each layer.


1 Answers

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.

like image 189
Piotr Kochański Avatar answered Sep 18 '22 23:09

Piotr Kochański