Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回JSON格式的异常_Json_Jersey - Fatal编程技术网

返回JSON格式的异常

返回JSON格式的异常,json,jersey,Json,Jersey,以JSON格式返回Jersey异常的最佳方法是什么? 这里是我的示例代码 public static class CompoThngExceptionMapper implements ExceptionMapper<Exception> { @Override public Response toResponse(Exception exception) { if (exception instanceof WebApplicationExc

以JSON格式返回Jersey异常的最佳方法是什么? 这里是我的示例代码

    public static class CompoThngExceptionMapper implements ExceptionMapper<Exception> {
    @Override
    public Response toResponse(Exception exception) {
        if (exception instanceof WebApplicationException) {
            WebApplicationException e = (WebApplicationException) exception;
            Response r = e.getResponse();
            return Response.status(r.getStatus()).entity(**HERE JSON**).build();
    } else {
            return null;

        }
    }
公共静态类CompoThngExceptionMapper实现ExceptionMapper{
@凌驾
公众响应(例外){
if(WebApplicationException的异常实例){
WebApplicationException e=(WebApplicationException)异常;
响应r=e.getResponse();
返回Response.status(r.getStatus()).entity(**此处为JSON**).build();
}否则{
返回null;
}
}

提前感谢!!!

取决于您想要返回的内容,但就我个人而言,我有一个
ErrorInfo
对象,看起来像这样:

public class ErrorInfo {
    final transient String developerMessage;
    final transient String userMessage;

    // Getters/setters/initializer
}
我将其作为我的
异常
的一部分传递,然后我使用Jackson的
对象映射器
异常映射器
中的
错误信息
对象创建一个JSON字符串。这种方法的好处是,您可以非常轻松地扩展它,因此添加状态信息、错误时间等等都是非常重要的添加另一个字段的情况

请记住,添加响应状态之类的内容有点浪费,因为这将返回HTTP头

更新

下面是一个完整的示例(在本例中,ErrorInfo包含更多字段,但您得到了总体思路):

导入javax.ws.rs.core.MediaType;
导入javax.ws.rs.core.Response;
导入javax.ws.rs.core.Response.ResponseBuilder;
导入javax.ws.rs.core.Response.Status;
导入javax.ws.rs.ext.ExceptionMapper;
导入javax.ws.rs.ext.Provider;
导入com.fasterxml.jackson.core.JsonProcessingException;
导入com.fasterxml.jackson.databind.ObjectMapper;
@提供者
公共类UnexpectedExceptionMapper实现ExceptionMapper
{
私有静态最终瞬态ObjectMapper MAPPER=新ObjectMapper();
@凌驾
公众响应(最终例外)
{
ResponseBuilder builder=Response.status(status.BAD\u请求)
.entity(defaultJSON(例外))
.type(MediaType.APPLICATION_JSON);
返回builder.build();
}
私有字符串defaultJSON(最终异常)
{
ErrorInfo ErrorInfo=新的ErrorInfo(null,exception.getMessage(),exception.getMessage(),(String)null);
尝试
{
返回MAPPER.writeValueAsString(errorInfo);
}
捕获(JsonProcessingException e)
{
返回“{\”消息\”:“发生内部错误\“}”;
}
}
}

避免导入Jackson类,但只使用纯JAX-RS类,我创建了json异常包装器,如下所示

创建ExceptionInfo包装器并为各种异常状态类型创建子类

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class ExceptionInfo {
    private int status;
    private String msg, desc;
    public ExceptionInfo(int status, String msg, String desc) {
        this.status=status;
        this.msg=msg;
        this.desc=desc;
    }

    @XmlElement public int getStatus() { return status; }
    @XmlElement public String getMessage() { return msg; }
    @XmlElement public String getDescription() { return desc; }
}

- - - - 

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.WebApplicationException;

/**
 * Create 404 NOT FOUND exception
 */
public class NotFoundException extends WebApplicationException {
    private static final long serialVersionUID = 1L;

    public NotFoundException() {
        this("Resource not found", null);
    }

    /**
     * Create a HTTP 404 (Not Found) exception.
     * @param message the String that is the entity of the 404 response.
     */
    public NotFoundException(String msg, String desc) {
        super(Response.status(Status.NOT_FOUND).entity(
                new ExceptionInfo(Status.NOT_FOUND.getStatusCode(), msg, desc)
        ).type("application/json").build());
    }

}
然后在资源实现中抛出异常,客户机将收到一个漂亮的json格式的http错误体

@Path("/properties")
public class PropertyService {
    ...
    @GET @Path("/{key}")
    @Produces({"application/json;charset=UTF-8"})
    public Property getProperty(@PathParam("key") String key) {
        // 200=OK(json obj), 404=NotFound
        Property bean = DBUtil.getProperty(key);
        if (bean==null) throw new NotFoundException();
        return bean;
    }   
    ...
}

- - - - 
Content-Type: application/json
{"status":404,"message":"Resource not found","description":null}

谢谢jgm。对不起。您如何对Jacson的
ObjectMapper
进行编码,以便从
ExceptionMapper
中的
ErrorInfo
对象创建JSON字符串?提前谢谢最后一个问题jgm。我在Jetty-Jersey环境中,并且我总是在异常中获得空值。getMessage().我只想返回状态描述。提前谢谢。这表明在某个地方抛出了一个没有消息的异常。只需更改ErrorInfo的创建,以适应您想要返回的任何内容。问题是所有异常都没有异常消息。我不知道是Jetty、Jersey还是Noideai如果它没有消息,它就没有消息。要么输入默认值,要么根据异常的类型生成一个。我不明白。这个
ExceptionInfo
在哪里使用?或者你认为
NotFoundException
应该扩展
ExceptionInfo
?@sja:See
NotFoundException(String msg,String desc)
构造函数。
@Path("/properties")
public class PropertyService {
    ...
    @GET @Path("/{key}")
    @Produces({"application/json;charset=UTF-8"})
    public Property getProperty(@PathParam("key") String key) {
        // 200=OK(json obj), 404=NotFound
        Property bean = DBUtil.getProperty(key);
        if (bean==null) throw new NotFoundException();
        return bean;
    }   
    ...
}

- - - - 
Content-Type: application/json
{"status":404,"message":"Resource not found","description":null}