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;

 public String getMessage() {
  return message;
package com.controller;

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

import com.exception.UserDefinedException;

public class ExceptionDemo {

 public String userDefinedExceptionDemo(){
  boolean exception = true;
   throw new UserDefinedException("exception in controller"); // throw user defined exception
  return "welcome";
 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



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


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.

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.
<h2>Default Error Page </h2> 
Package structure

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