问题描述
我使用 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
这篇关于Jersey 2 异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!