Jersey 2 exception handing

2019-06-10 05:55发布

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

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

This is the code from error object:

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条回答
\"骚年 ilove
2楼-- · 2019-06-10 06:36

Setting the following server property to true resolves this issue.

jersey.config.server.response.setStatusOverSendError
查看更多
Luminary・发光体
3楼-- · 2019-06-10 06:42

Just for completness below are two alternative ways to set mentioned Jersey property:

Programmatically:

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

Or inside 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>
查看更多
登录 后发表回答