Spring MVC - Exception handling with SimpleMappingExceptionResolver


SimpleMappingExceptionResolver : - This resolver enables you to take the class name of any exception that might be thrown and map it to a view name.

Example : will see how the SimpleMappingExceptionResolver work.

1. Defined exception class ( will throw from controller)
 
package com.exception;

public class UserDefinedException extends RuntimeException{


 private static final long serialVersionUID = 1L;
 public String message;
 
 public UserDefinedException(String message) {
  this.message = message;
 }

 @Override
 public String getMessage() {
  return message;
 }
}
2.Controller
 
package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.exception.UserDefinedException;

@Controller
public class ExceptionDemo {

 @RequestMapping("/welcome")
 public String userDefinedExceptionDemo(){
  boolean exception = true;
  
  if(exception){
   throw new UserDefinedException("exception in controller"); // throw user defined exception
  }
  return "welcome";
 }
 
 @RequestMapping("/hello")
 public String defaultExceptionDemo(){
  
  String temp = null;
  temp.toString(); // will throw null pointer exception
  return "hello";
 }
} 

first method - on "../welcome" (URL) will throw user defined exception
second method - on "/hello" (URL) will throw null pointer exception
3.Configuration
 


 

 
  
   /WEB-INF/jsps/
  
  
   .jsp
  
 
 
 
      
         
            exception
         
      
   
   


On first entry simply define its "exceptionMappings" property by providing a list of exception/view pair values:
 

 
      
         
            exception
         
      
   
  

Above, we are map the UserDefinedException to the view "exception". make sure that he view declaration is correct and the actual pages exist.
 
 
 
on above entry we defined "defaultErrorView" wich is used for default error page, means if any error other than exceptions which are defined in "exceptionMappings" thrown  will redirect to defaulterror page.
4.View

Defined two jsps, one is for user defined exceptions and other for default error page.
In the JSP page, we can access the exception instance via ${exception}.  "message" is variable in UserDefinedException class.
exception.jsp
 
<html>
<body>
 <h2>${exception.message}</h2>
</body>
</html>
defaulterror.jsp
 
<html>
<body>
<h2>Default Error Page </h2> 
</body>
</html>
Package structure

Result:
When you hit the url "http://localhost:8080/SpringMVCDemo/welcome"  it will throw UserDefinedException and will show the exception page.
When you hit the url "http://localhost:8080/SpringMVCDemo/hello"  it will throw NullPointerException(which is not defined in exceptionMappings, so will go to default error page.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...