泽西2异常处理

时间:2014-08-21 07:35:01

标签: java web-services rest jersey-2.0

我使用Jersey 2.10异常映射器类来处理异常。我想返回错误状态和JSON正文以获取错误信息。我希望得到类似的答案:

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正文。我得到的是:

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,那么我会按预期获得响应正文

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}

请帮我弄清楚这个问题的解决方法。

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

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

2 个答案:

答案 0 :(得分:2)

以下是完整性,有两种方法可以设置提到的Jersey属性:

编程:

new ResourceConfig()
       .property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true);

或者在web.xml中:

<servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  ....
  <init-param>
    <param-name>jersey.config.server.response.setStatusOverSendError</param-name>
    <param-value>true</param-value>
  </init-param>
</servlet>

答案 1 :(得分:1)

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

jersey.config.server.response.setStatusOverSendError