如何捕获RESTEasy Bean验证错误?

K. *_*ddy 3 java rest jax-rs resteasy restful-architecture

我正在使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Pio*_*ski 9

您应该使用异常映射器.例:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

其中Error可能是这样的:

@XmlRootElement
public class Error{
   private String message;
   //getter and setter for message field
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这正是我正在寻找的.非常感谢. (2认同)