Pages

Spring MVC - Exception Handling

Hope you knows MVC. :)
When you comes to Spring MVC there are multiple ways that you can handle exceptions. So in here I will show you some of ways that how to handle exceptions in a proper way.
If you have more than good solutions feel free to add it as comments.
Following solutions are one way to handle exceptions in web application, other than this you can use web.xml error-page tag to handle exceptions but it has many drawbacks. 

1. Here is the default way to handle exceptions. You can use another page to show some user friendly message instead of ugly message. 

 @RequestMapping(value = "/exception1", method = RequestMethod.GET)  
   public String exception1() {  
     throw new NullPointerException("Throwing null pointer exception");  
   }  
   @ExceptionHandler(NullPointerException.class)  
   public String handleException1(NullPointerException e) {  
     return "error/exception1";  
   }  

2. We generate the following exception using ajax and show it in same page as inline html.

Here is the code snippet in controller

 @RequestMapping(value = "/exception2", method = RequestMethod.GET)  
   public String exception2() {  
     throw new IndexOutOfBoundsException("Ajax Exception inline text");  
   }  
   @ExceptionHandler(IndexOutOfBoundsException.class)  
   @ResponseBody  
   public String handleException2(IndexOutOfBoundsException ex) {  
     return ex.getMessage();  
   }  

Here is Ajax code snippet

 function exception2()  
 {  
   $.ajax({  
     type: 'GET',  
     url: "/exception2",  
     success: function(data)  
     {  
       $('#message1').empty().html(data).show();  
     },  
     error:function(data)  
     {  
       alert('error');  
     }  
   });  
   return false;  
 }  

3. Following shows that ugly page with some custom messages (That would be nice :D)
It shows the HTTP status code in that page

 @RequestMapping(value = "/exception3", method = RequestMethod.GET)  
   public String exception3() {  
     throw new IllegalStateException("Exception3 with response status");  
   }  
   @ExceptionHandler(IllegalStateException.class)  
   @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "exception3")  
   public ModelAndView handleException3(IllegalStateException ex, HttpServletResponse response) throws IOException {  
     return new ModelAndView();  
   }  

Here are some of ways to handle exceptions in spring mvc. You can found the complete project here
https://github.com/rajithd/spring-mvc-exception-handling