【问题标题】:ExceptionHandler returning JSON or XML not working in spring mvc 3返回JSON或XML的ExceptionHandler在spring mvc 3中不起作用
【发布时间】:2011-06-24 08:00:06
【问题描述】:

代码是这样的:

   @Controller
    public class TestController {

        @RequestMapping(value = "/testerror", method = RequestMethod.GET)
        public @ResponseBody ErrorTO testerror(HttpServletRequest request,HttpServletResponse response) {
           throw new ABCException("serious error!");
        }


        @ExceptionHandler(ABCException.class)
        public  @ResponseBody ErrorTO handleException(ABCException ex,
                HttpServletRequest request, HttpServletResponse response) {
            response.setStatus(response.SC_BAD_REQUEST);
            return new ErrorTO(ex.getMessage());
        }


     @RequestMapping(value = "/test", method = RequestMethod.GET)
    public @ResponseBody ErrorTO test(HttpServletRequest request, 
                                      HttpServletResponse response) {
        ErrorTO error = new ErrorTO();
        error.setCode(-12345);
        error.setMessage("this is a test error.");
        return error;
    }

}

当我尝试 curl -H "Accept:application/json" -v "http://localhost.com:8080/testerror" 我收到了这个错误: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - 找不到支持返回类型 [class com.kibboko.poprocks.appservices.dtos.ErrorTO] 和 [application/json] 的 HttpMessageConverter

但是如果我尝试 curl -H "Accept:application/json" -v "http://localhost.com:8080/test",工作并返回 json 响应。 “应用程序/xml”也可以。

异常处理程序有什么特别之处我需要处理以便它可以与 json 或 xml 一起使用吗?谢谢!

【问题讨论】:

    标签: exception-handling spring-mvc


    【解决方案1】:

    似乎AnnotationMethodHandlerExceptionResolver 有自己的HttpMessageConverters 数组。您需要将其配置为使用与AnnotationMethodHandlerAdapter 相同的数组。

    但是,隐式声明 AnnotationMethodHandlerAdapter 时可能会很复杂。也许声明以下FactoryBean 可能在所有情况下都有帮助:

    public class AnnotationMethodHandlerExceptionResolverFactoryBean
            implements FactoryBean<AnnotationMethodHandlerExceptionResolver> {
        @Autowired
        private AnnotationMethodHandlerAdapter a;
    
        public AnnotationMethodHandlerExceptionResolver getObject()
                throws Exception {
            AnnotationMethodHandlerExceptionResolver r = new AnnotationMethodHandlerExceptionResolver();
            r.setMessageConverters(a.getMessageConverters());
            return r;
        }
    
        ...
    }
    

    【讨论】:

    • 这真的很麻烦。是否有可能找到更简单的解决方案?你能给我一个工作的例子吗?
    • @Bobo:您是否尝试在您的上下文中声明该 bean?它应该可以正常工作。
    • @axtavt:对不起,我是 Spring 的真正新手。 “在您的上下文中声明该 bean”是指在 spring 配置文件中声明它?
    • @axtavt:所以当 Spring 需要异常解析器时,他会使用这个 FactoryBean,对吧?!我们不需要在@ExceptionHandler注解的方法中手动调用getObject(),对吧?
    【解决方案2】:

    似乎是一个已知的 Spring 错误(已在 3.1 M1 中修复)

    https://jira.springsource.org/browse/SPR-6902

    【讨论】:

      猜你喜欢
      • 2018-12-10
      • 2021-05-22
      • 2011-06-18
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2011-09-13
      • 2013-05-23
      相关资源
      最近更新 更多