本文介绍了从Spring Exception Handler返回JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面提到的Spring代码来处理异常并将响应返回给客户端.由于我在这里使用了ResponseBody注释,因此我期望spring在发生错误的情况下返回JSON响应,但是我看到下面的响应在客户端收到(JSON响应位于responseText内部,而不是直接返回给客户端).请告知我如何将JSON响应返回给Caller-

I'm using below mentioned Spring code to handle exception and return response to client. 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). Please advice how I can return JSON response to Caller-

在客户端收到的回复:-

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

春季代码:-

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

推荐答案

我认为是@ResponseBody批注阻止了spring将MarsResponse对象编组为JSON对象.尝试将其删除并再次检查.

I think it's your @ResponseBody annotation that is preventing spring from marshalling your MarsResponse Object to a JSON Object. Try removing that and checking again.

这篇关于从Spring Exception Handler返回JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:34