5

I have been trying to get exception handling working in my simple Spring 3 based ReST web services. Based on everything I have seen, there is a bug that prevents this from working automatically with the @ResponseBody and @ExceptionHandler annotations

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

So given that it isn't supported until Spring 3.1 or 3.0.6, what is the current best method for doing exception handling? I have seen numerous posts but haven't found a clear answer that has worked for me. An ideal solution would be one that automatically provides support for both xml and json

  • Do I have to manually define the entire marshalling setup? Won't this remove the need for the annotations that make using Spring 3 rest support worth it?
  • Seems in order to manually define marshalling (i.e. Jaxb2Marshaller) I need to add a new dependency on spring-ws which is a bit of a pain
  • Is it easier to just define a 'Response' object that all my methods return and wrap all functions in try/catch blocks?
Collin Peters
  • 4,353
  • 3
  • 29
  • 36
  • related: http://stackoverflow.com/questions/6014784/serialize-exceptions-to-json-with-spring-mvc – Bozho Jun 07 '11 at 16:41

2 Answers2

7

You can redirect on error and then return something in @ResponseBody:

@ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception  exception) {
    return new ModelAndView("redirect:errorMessage?error="+exception.getMessage());
} 

@RequestMapping(value="/errorMessage", method=RequestMethod.GET)
@Responsebody
public String handleMyExceptionOnRedirect(@RequestParameter("error") String error) {
    return error;
} 

Little ugly, but this is just work around till the fix will be available.

Tom Verelst
  • 15,324
  • 2
  • 30
  • 40
danny.lesnik
  • 18,479
  • 29
  • 135
  • 200
  • 2
    +1 for the workaround. This will also mean that the client will have to handle the redirect. If he is expecting a result, it might create a problem. Just some heads up... Cheers! – despot Jul 18 '11 at 10:02
  • Another workaround [here](http://stackoverflow.com/questions/5097134/spring-exceptionhandler-does-not-work-with-responsebody/5097584#5097584) – Tahir Akhtar Sep 01 '11 at 11:34
0

This is a good workaround, but with one addition. The @ExceptionHandler(Exception.class) should be @ExceptionHandler(MyException.class, YourException.class) as you can get into a loop using the general Exception class.

You can then test for (ex instanceof Myexception) to determine the message to display if need be.