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;
}
Setting the following server property to true resolves this issue.
Just for completness below are two alternative ways to set mentioned Jersey property:
Programmatically:
Or inside web.xml: