2012-05-09 55 views
3

我正在使用JBoss-7.1和RESTEasy开发一个简单的RESTFul服务。 我有一个REST服务,叫的CustomerService如下:如何捕获RESTEasy Bean验证错误?

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

这里的时候,我打的网址http://localhost:8080/SomeApp/customers/-1然后@Min约束将失败,并在屏幕上显示堆栈跟踪。

是否有一种方法来捕获这些验证错误,以便我可以准备一个带有适当错误消息的xml响应并显示给用户?

回答

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

其中错误可能是这样的:

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

然后你会得到裹成XML错误消息。

+1

这就是我正在寻找的。非常感谢。 –

+0

hi siva,你是如何将有意义的错误对象转换出来的,返回Set >的cex.getConstraintViolations(),你如何在这里识别T泛型? –

+1

这对Wildfly 8.2.0(HV 5.1.3,RestEasy 3.0.10)来说并不适用,ExceptionMapper被完全忽略了(异常映射器永远不会被调用,响应中的实体不是I' m设置,由于不匹配,我得到一个ProcessingException)。其他例外映射工作完美无缺。你认为可能是什么原因? – jpangamarca