使用spring-mvc将异常序列化为JSON [英] Serialize exceptions to JSON with spring-mvc

查看:112
本文介绍了使用spring-mvc将异常序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@RequestMapping(..)
@ResponseBody
public SearchResponse search(SearchRequest request) throws SearchException { .. }

我想返回请求者:

  • 在一切正常的情况下以JSON序列化的搜索响应
  • 如果抛出SearchException,则
  • JSON序列化的异常详细信息.

第一部分工作正常(在类路径和<mvc:annotation-driven />上具有Jackson),但是我看不到将异常序列化为json的简单方法.

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.

我可以注册一个自定义处理程序,然后从那里编写一个JSON字符串,但是我可能还需要XML序列化,这意味着我将需要在处理程序中使用条件.还没准备好吗?

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?

推荐答案

这是有效的方法:我使用了

Here's what worked: I took axtavt's suggestion (annotating it with @Component), and added this method to the controller:

@ExceptionHandler(CustomException.class)
public @ResponseBody CustomException handleException(CustomException ex) {
    return ex;
}

这篇关于使用spring-mvc将异常序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆