我的目标是在发生404错误时返回一个错误bean并附带描述性信息,同时返回相同的MIME类型。
我有一个查找资源,在URI基础上返回指定对象的XML或JSON格式(我已经设置了com.sun.jersey.config.property.resourceConfigClass servlet参数,因此不需要Accept头。我的JAXBContextResolver在其类型列表中具有ErrorBean.class,并且为此类返回了正确的JAXBContext,因为我可以在日志中看到)。
例如:http://foobar.com/rest/locations/1.json
我有一个查找资源,在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 No Content 的响应。我已经绕过了这个问题,如果返回一个字符串并指定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!"}