Wednesday, November 27, 2013

Tip: Parent controller to handle exception in Spring MVC

Spring MVC is a powerful framework and I got a tip that can be useful. Spring MVC uses the technique of something called Controller which can be bound to handle the different user request to do a prerequisites before showing the user a specific page he requested.
In case you got many controllers and you need to handle the common exceptions for your application. You can do that by making a parent class which I prefer to call Parent Controller that can handle the exception as the bellow examples shows. Then you can extend that class in your other different controllers.
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

public class ParentController {

 private ModelAndView modelAndView;
 
 @ExceptionHandler(NullPointerException.class)
 public ModelAndView handleNullPointerException(NullPointerException e) {
  // Display the error page
  modelAndView = new ModelAndView("404");
  modelAndView.addObject("message", "NullPointerException occured - " + System.currentTimeMillis());
  return modelAndView;
 }
}