2010-05-20 50 views
11

我的目標是在沒有找到對象的情況下,在404上返回一個帶有描述性消息的錯誤bean,並返回請求的相同MIME類型。返回JSON或XML作爲澤西島中的例外

我有一個查找資源,它將基於URI返回XML或JSON中的指定對象(我已經設置了com.sun.jersey.config.property.resourceConfigClass servlet參數,因此我不需要Accept頭。我的JAXBContextResolver在它的類型列表中有ErrorBean.class,並且爲這個類返回正確的JAXBContext,因爲我可以在日誌中看到)。

如:http://foobar.com/rest/locations/1.json

@GET 
@Path("{id}") 
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) 
public Location getCustomer(@PathParam("id") int cId) { 
    //look up location from datastore 
    .... 
    if (location == null) { 
     throw new NotFoundException("Location" + cId + " is not found"); 
    } 

} 

而且我NotFoundException看起來是這樣的:

public class NotFoundException extends WebApplicationException { 

    public NotFoundException(String message) { 
     super(Response.status(Response.Status.NOT_FOUND). 
       entity(new 
         ErrorBean(
          message, 
          Response.Status.NOT_FOUND.getStatusCode() 
         ) 
       .build()); 
    } 

} 

的ErrorBean如下:

@XmlRootElement(name = "error") 
public class ErrorBean { 

    private String errorMsg; 
    private int errorCode; 

     //no-arg constructor, property constructor, getter and setters 
     ... 

} 

不過,我總是得到一個204沒有內容當我嘗試時的迴應 這個。我已經砍死左右,如果我返回一個字符串,並指定MIME類型能正常工作:

public NotFoundException(String message) { 
    super(Response.status(Response.Status.NOT_FOUND). 
      entity(message).type("text/plain").build()); 
} 

我也試圖返回一個ErrorBean作爲一種資源。這工作得很好:

{"errorCode":404,"errorMsg":"Location 1 is not found!"} 

回答

9

對於那些今後發生類似的問題...

原來我的代碼是在最後確定。我把頭髮拉出來,所以我重寫了這個模塊,並且還沒有到達任何地方。我的瀏覽器只會坐在那裏永遠掛起。我開始用LiveHTTPHeaders(firefox add-on)檢查標題,並注意到這種情況發生時Content-Length大於零。然後我用hurl.it進行了測試,發現身體正常恢復。瀏覽器會處理XML響應,但不會顯示JSON(因此掛起)。這對我來說很好,因爲這純粹是應用程序使用的API,而不是用戶。有關於映射例外的信息在Jersey wiki

HTTP/1.1 404 Not Found 
Content-Type: application/json 
Date: Fri, 21 May 2010 06:39:28 GMT 
Server: Google Frontend 
Cache-Control: private, x-gzip-ok="" 
Transfer-Encoding: chunked 

{ 
    "errorCode": "404", 
    "errorMsg": "Could not retrieve entity of kind Location with key Location(10)" 
}