Spring MVC provides a great way to handle exceptions and errors.
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.
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
@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: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.importorg.springframework.web.bind.annotation.ExceptionHandler;//..@ExceptionHandler(IOException.class)publicString exception(Exception e) {//..return"error";}
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. importorg.springframework.web.bind.annotation.ControllerAdvice;//..@ControllerAdvicepublicclassExceptionControllerAdvice {@ExceptionHandler(Exception.class)publicString 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.If you have defined just the
<mvc:annotation-driven></mvc:annotation-driven>
it wouldn’t work. The @ControllerAdvice will simply wont be loaded. So always remember to use in Spring configuration.