使用 spring-mvc 将异常序列化为 JSON
@RequestMapping(..)
@ResponseBody
public SearchResponse search(SearchRequest request) throws SearchException { .. }
我想返回给请求者:
- JSON 序列化的搜索响应,如果一切正常,
- 则 JSON 序列化的异常详细信息(如果抛出
SearchException
)。
第一部分工作正常(在类路径上有 Jackson 和
),但我没有看到将异常序列化为 json 的简单方法。
我可以注册一个自定义处理程序,并从那里编写一个 JSON 字符串,但我可能还需要 XML 序列化,这意味着我需要在处理程序中使用条件。难道没有为此准备一些东西吗?
@RequestMapping(..)
@ResponseBody
public SearchResponse search(SearchRequest request) throws SearchException { .. }
I want to return to the requester:
- JSON-serialized search response in case everything is fine
- JSON-serialized exception details if
SearchException
is thrown.
The first part works fine (having Jackson on the classpath and <mvc:annotation-driven />
) but I don't see an easy way to serialize the exception as json.
I can register a custom handler, and write a JSON string from there, but I may also need XML serialization, which will mean I'll need conditionals in the handler. Isn't there something ready for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是有效的:我采取了 axtavt的建议(用
@Component
注释),并将此方法添加到控制器中:Here's what worked: I took axtavt's suggestion (annotating it with
@Component
), and added this method to the controller: