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(). We mapped IOException.class to this method using @ExceptionHandler annotation.

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. However this is a way to overcome this problem. @ControllerAdvice annotation is at your service for that.

@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.

One thing worth noting here is that Spring configuration must define mvc namespace in order to identify @ControllerAdvice annotation. Thus you must define following in your spring-servlet.xml file.

    <mvc:annotation-driven>
</mvc:annotation-driven>
If you have defined just the it wouldn’t work. The @ControllerAdvice will simply wont be loaded. So always remember to use in Spring configuration.

Next Post Newer Posts Previous Post Older Posts Home