How to catch RESTEasy Bean Validation Errors?

微笑、不失礼 提交于 2019-12-29 07:15:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10516516/how-to-catch-resteasy-bean-validation-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!