如何捕获RESTEasy Beanvalidation错误?

我正在使用JBoss-7.1和RESTEasy开发一个简单的RESTFul服务。 我有一个名为CustomerService的REST服务,如下所示:

@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; } } 

当我点击URL http:// localhost:8080 / SomeApp / customers / -1时, @ Min约束将失败并在屏幕上显示堆栈跟踪。

有没有办法捕获这些validation错误,以便我可以准备一个带有正确错误消息的xml响应并显示给用户?

您应该使用exception映射器。 例:

 @Provider public class ValidationExceptionMapper implements ExceptionMapper { 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 } } 

其中Error可能是这样的:

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

然后你会得到包装成XML的错误信息。