在 Jersey 中返回 JSON 或 XML 异常

发布于 2024-09-02 13:53:54 字数 1849 浏览 2 评论 0原文

我的目标是在未找到对象时在 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!"}

My goal is to have an error bean returned on a 404 with a descriptive message when a object is not found, and return the same MIME type that was requested.

I have a look up resource, which will return the specified object in XML or JSON based on the URI (I have setup the com.sun.jersey.config.property.resourceConfigClass servlet parameter so I dont need the Accept header. My JAXBContextResolver has the ErrorBean.class in its list of types, and the correct JAXBContext is returned for this class because I can see in the logs).

eg: 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");
     }

}

And my NotFoundException looks like this:

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());
    }

}

The ErrorBean is as follows:

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

    private String errorMsg;
    private int errorCode;

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

}

However, I'm always getting a 204 No Content response when I try this. I have hacked around, and if I return a string and specify the mime type this works fine:

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

I have also tried returning an ErrorBean as a resource. This works fine:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瘫痪情歌 2024-09-09 13:53:54

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

结果证明我的代码最终没问题。我很抓狂,所以我重写了这个模块,但仍然没有任何进展。我的浏览器只会坐在那里并永远挂起。我开始使用 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)"
}

For those with similar issues in the future ...

Turns out my code was OK in the end. I was pulling my hair out, so I rewrote this module, and was still not getting anywhere. My browser would just sit there and hang forever. I started inspecting the headers with LiveHTTPHeaders (firefox add-on), and noticed when this happened Content-Length was larger then zero. I then tested with hurl.it and found out the body was returning normally. The browser would handle the XML response fine, but wouldnt ever display the JSON (thus the hanging). This is fine for my purpose as this is purely an API for application consumption and not for users. There is information on mapping exceptions at the 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)"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文