在Jersey中返回JSON或XML的异常

11
我的目标是在发生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
@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!"}
1个回答

9

对于将来遇到类似问题的人...

结果最终证明我的代码是没有问题的。我一度感到很沮丧,所以我重写了这个模块,但仍然没有任何进展。我的浏览器只会停留在那里,永远不会加载出来。我开始使用LiveHTTPHeaders(Firefox插件)检查头文件,并注意到当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)"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接