从Spring Exception Handler返回JSON响应

编程入门 行业动态 更新时间:2024-10-10 10:32:37
本文介绍了从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响应

本文发布于:2023-11-28 04:05:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Exception   Spring   JSON   Handler

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!