我的目標是在沒有找到對象的情況下,在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!"}