Spring MVC provides a great way to handle exceptions and errors.
@ExceptionHandler annotation is core to this feature. For each Spring controller we can simply define a method that automatically gets called if a given exception occurs.
For example:
import org.springframework.web.bind.annotation.ExceptionHandler;
//..
@ExceptionHandler(IOException.class)
public String exception(Exception e) {
//..
return "error";
}
Thus whenever an IOException is raised from any controller method will call the above method exception().
But there is one short coming of this annotation is that it only handles exception getting raised from the controller where it is defined. It will not handle exceptions getting raised from other
controllers.
So to overcome this problem we have,
@ControllerAdvice annotation.
This annotation is used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods.
import org.springframework.web.bind.annotation.ControllerAdvice;
//..
@ControllerAdvice
public class ExceptionControllerAdvice {
@ExceptionHandler(Exception.class)
public String exception(Exception e) {
return "error";
}
}
Thus if we define our @ExceptionHandler annotation on method in @ControllerAdvice class, it will be applied to all the controllers. Spring configuration must define mvc namespace in order to identify @ControllerAdvice annotation.
So you must define following in your spring-servlet.xml file.
< mvc:annotation-driven/>
If you have defined just the it wouldnt work.
The @ControllerAdvice will simply wont be loaded.
So always remember to use <mvc:annotation-driven/> in Spring configuration.
0 Comment(s)