【问题标题】:How to catch RESTEasy Bean Validation Errors?如何捕获 RESTEasy Bean 验证错误?
【发布时间】:2012-05-17 23:50:39
【问题描述】:

我正在使用 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 约束将失败并在屏幕上显示堆栈跟踪。

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

【问题讨论】:

    标签: java rest jax-rs resteasy restful-architecture


    【解决方案1】:

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

    @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 的错误信息。

    【讨论】:

    • 这正是我想要的。非常感谢。
    • 嗨湿婆,你是如何将有意义的错误对象从 cex.getConstraintViolations() 返回 Set> 的,你如何在这里识别 T 泛型类型?
    • 这不适用于 Wildfly 8.2.0(HV 5.1.3,RestEasy 3.0.10),ExceptionMapper 被完全忽略(异常映射器从未被调用,响应中的实体不是我设置的类型,由于不匹配,我得到了 ProcessingException)。其他异常映射器工作完美。您认为可能是什么原因?
    • @jpangamarca:RestEasy 3.0.10 不会抛出 ConstraingViolationException,而是它自己的 ResteasyViolationException。您的 ValidationExceptionMapper 应该处理此异常。 (这应该在 RestEasy 3.0.12 中修复)。见issues.jboss.org/browse/RESTEASY-1137
    • 这是错误的。请参考stackoverflow.com/questions/44308101/…
    猜你喜欢
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多