How to catch RESTEasy Bean Checker 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 click url http: // localhost: 8080 / SomeApp / customers / -1 , then the @Min constraint will fail and show the stack on the screen.

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

+3
source share
1 answer

You must use an exception handler. 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 the error might be something like this:

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

You will then receive an error message enclosed in XML.

+9

All Articles