我正在使用JBoss-7.1和RESTEasy开发一个简单的RESTFul服务。我有一个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约束将失败并在屏幕上显示堆栈跟踪。
有没有办法捕获这些验证错误,以便我可以准备带有正确错误消息的 xml 响应并显示给用户?
您应该使用异常映射器。例:
@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
}
}
其中错误可能是这样的:
@XmlRootElement
public class Error{
private String message;
//getter and setter for message field
}
然后,您将收到包装到 XML 中的错误消息。