泽西岛2异常处理 [英] Jersey 2 exception handing

查看:92
本文介绍了泽西岛2异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey 2.10异常映射器类来处理异常.我想返回错误状态和JSON正文以获取错误信息.我想得到类似于以下内容的回复:

I am using Jersey 2.10 exception mapper class for handling exceptions. I want to return error status and JSON body for the error info. I want to get a response similar to this:

400 Bad Request
X-Powered-By:  Servlet/3.0
Content-Length:  152
Content-Type:  application/json
Content-Language:  en-AU
Date:  Thu, 21 Aug 2014 07:21:40 GMT

{"errors":[{"code":"LKVBS182","type":"ERROR","message":"COUNTRY NAME IS NOT DEFINED IN DATA-BASE"}],"status":"ERROR","errorStatus":"Bad Request","errorCode":400}

Jersey没有在响应中发送JSON正文.我得到的是这样的:

Jersey is not sending the JSON body in the response. What I get is this:

400 Bad Request
Content-Length:  161
Content-Type:  text/html;charset=UTF-8
Connection:  Close
Date:  Thu, 21 Aug 2014 07:29:22 GMT

Error 400: Bad Request

如果我将状态码更改为200,那么我将得到预期的响应正文

If I change the status code to 200 then I get the response body as expected

200 OK
X-Powered-By:  Servlet/3.0
Content-Length:  152
Content-Type:  application/json
Content-Language:  en-AU
Date:  Thu, 21 Aug 2014 07:21:40 GMT

{"errors":[{"code":"LKVBS182","type":"ERROR","message":"COUNTRY NAME IS NOT DEFINED IN DATA-BASE"}],"status":"ERROR","errorStatus":"Bad Request","errorCode":400}

请帮助我找出解决此问题的方法.

Please help me figure out the resolution for this issue.

异常映射器在错误对象中填充错误消息和状态.这是异常映射器代码:

The exception mapper populates error message and status in error object. Here is the exception mapper code:

public Response toResponse(ServiceException exception) {
        List<MyResponseError> myErrors= exception.getMyErrors();        
        ErrorsDTO errors = new ErrorsDTO(ERROR_STATUS,myErrors);        
        return errors.generateResponse();       
    }

这是错误对象的代码:

public Response generateResponse() {
        if(this.errorStatus==null){
            this.errorStatus= Status.NOT_FOUND;
        }
        this.errorCode= this.errorStatus.getStatusCode();
        //TODO response status should be set to this.errroStatus. 
        //Jersey does not allow JSON response with status code other than 200
        ResponseBuilder builder = Response.status(Status.OK);
        builder.entity(this);
        builder.type(MediaType.APPLICATION_JSON);
        Response response = builder.build();
        return response;
}

推荐答案

将以下服务器属性设置为true可解决此问题.

Setting the following server property to true resolves this issue.

jersey.config.server.response.setStatusOverSendError

这篇关于泽西岛2异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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