Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExceptionHandler returning JSON or XML not working in spring mvc 3

code is like this:

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

}

when I tried curl -H "Accept:application/json" -v "http://localhost.com:8080/testerror" I got this error: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Could not find HttpMessageConverter that supports return type [class com.kibboko.poprocks.appservices.dtos.ErrorTO] and [application/json]

but if I try curl -H "Accept:application/json" -v "http://localhost.com:8080/test", worked and returned json response. "application/xml" worked too.

Is there anything special about exception handler I need to take care of so it can work with json or xml? Thanks!

like image 553
Bobo Avatar asked Feb 09 '11 17:02

Bobo


2 Answers

It appears that AnnotationMethodHandlerExceptionResolver has its own array of HttpMessageConverters. You need to configure it to use the same array as used by AnnotationMethodHandlerAdapter.

However, it can be complicated when AnnotationMethodHandlerAdapter is declared implicitly. Perhaps declaring the following FactoryBean may help in all cases:

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

    ...
}
like image 158
axtavt Avatar answered Sep 21 '22 23:09

axtavt


Seems like a known Spring bug (Fixed in 3.1 M1)

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

like image 38
Eran Medan Avatar answered Sep 20 '22 23:09

Eran Medan