Friday, 23 July 2010

Spring MVC ExceptionHandler needs to be in same class

Had a frustrating evening (pet project) trying to get Spring 3.0 MVC's annotation based exception handler to work.

All the examples seemed straight forwards:

Just annotate a method in a controller:
import org.springframe...ExceptionHandler;
import org.springframe...ModelAndView;
import org.springframe...Controller;
....
@Controller
public class MyController {
....
@ExceptionHandler(SomeException.class)
public ModelAndView myExceptionHandler(
    SomeException exception){
  blah
}
...
}


But it just would never catch my exceptions. Very frustrating.

But in the end a google search to the end of the world where someone mentioned in the comments that the exceptionhandler method have to be be in the same class as the method throwing the exception.

Very odd restriction compared to Spring's usual very agile and generic annotation.

So I added my handlers to my abstract controller class that all my controllers extend and problem solved, with some hair still intact.

6 comments:

Lisak said...

Hi Ivar, do you know how would I do the same If I hadn't extend any abstract controller but I was using only DefaultAnnotationHandlerMapping ? I'm going crazy about this, I got stuck for two hours trying to figure that out ...

kolodrevskiy said...

Hey,

Did you guys found a good workaround for this?

Rubens Mariuzzo said...

Thanks!

Somaiah said...

Wouldn't it be a better solution be to create a generic exception handler to handle all exceptions using Spring's default exception handler, and then override exception handlers specific to controllers using the annotation?

careerPleasure said...

I have the same problem. Can you guys give some example programs of how to fix it.

Stevo Slavić said...

As of Spring 3.2 @ControllerAdvice is available for shared/common @ExceptionHandler methods.

See this SO entry.