2012-05-09 89 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