简体   繁体   English

从Spring Exception Handler返回JSON响应

[英]Returning JSON response from Spring Exception Handler

I'm using below mentioned Spring code to handle exception and return response to client. 我正在使用下面提到的Spring代码来处理异常并将响应返回给客户端。 Since I have used ResponseBody annotation here , I was expecting spring to return JSON response in case of error but I see below response received at client end (JSON response is inside responseText instead of directly return to client). 由于我在这里使用了ResponseBody注释,因此我期望spring在发生错误的情况下返回JSON响应,但是我看到下面的响应在客户端收到(JSON响应位于responseText内部,而不是直接返回给客户端)。 Please advice how I can return JSON response to Caller- 请建议我如何将JSON响应返回给Caller-

Response received at Client End :- 在客户端收到的回复:-

Object {readyState: 4, responseText: "{"status":false,"msg":"User Data not available","r…"MARSAPI003","noOfRecords":0,"responseList":null}", responseJSON: Object, status: 403, statusText: "Forbidden"}

Spring Code :- 春季代码:-

@ExceptionHandler(MarsUnAuthorizedOperation.class)
@ResponseBody
@ResponseStatus(value=HttpStatus.FORBIDDEN)
public MarsResponse unAuthorizedOperationExceptionHandler(final Exception ex){
    final MarsResponse response = new MarsResponse();
    response.setNoOfRecords(0);
    response.setMsg(ex.getMessage());
    response.setResponseCode(marsMessageProperties.getUnauthorizedOperationErrorCd());
    response.setResponseMessage(marsMessageProperties.getUnauthorizedOperationErrorMsg());
    response.setStatus(false);
    return response;
}

I think it's your @ResponseBody annotation that is preventing spring from marshalling your MarsResponse Object to a JSON Object. 我认为是@ResponseBody批注阻止了spring将MarsResponse对象编组为JSON对象。 Try removing that and checking again. 尝试将其删除并再次检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM