返回在泽西州例外的JSON或XML [英] Returning JSON or XML for Exceptions in Jersey

查看:167
本文介绍了返回在泽西州例外的JSON或XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在没有找到对象时,在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){
//从数据存储区查找位置
....
if(location == null){
抛出新的NotFoundException(位置+ cId +未找到);
}

}

我的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构造函数,属性构造函数,getter和setter
...

}

然而,我总是得到一个 204无内容当我尝试这个回应。我已经被黑客攻击了,如果我返回一个字符串并指定了这个mime类型,这个工作正常:

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

我也试过返回一个ErrorBean作为资源。这样做很好:

  {errorCode:404,errorMsg:找不到位置1} 


解决方案

对于那些在将来有类似问题的人来说, p>

结果我的代码是OK的。我把我的头发拉出来,所以我重写了这个模块,还没到任何地方。我的浏览器只会坐在那里永久挂我开始使用LiveHTTPHeaders(firefox add-on)检查标题,并注意到发生这种情况时Content-Length大于零。然后我用 hurl.it 测试,发现身体正常返回。浏览器将处理XML响应,但不会显示JSON(因此挂起)。这对我的目的是好的,因为这纯粹是应用程序消费的API,而不是用户的API。有关于泽西维基

  HTTP / 1.1 404未找到
内容类型:application / json
日期:Fri ,2010年5月21日06:39:28 GMT
服务器:Google前端
缓存控制:私有,x-gzip-ok =
传输编码:分块

{
errorCode:404,
errorMsg:无法检索实体的位置与键位置(10)
}


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!"}

解决方案

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)"
}

这篇关于返回在泽西州例外的JSON或XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆