Spring MVC Exceptional Handling using @ExceptionHandler example

In this post , we will see how to do exceptional handling in Spring MVC using @ExceptionalHandler. You can use @ExceptionHandler to redirect to error view when exception occurs.
Lets understand this with the help of example:

Source code:

click to begin

20KB .zip

1) Create a dynamic web project using maven in eclipse named “SpringMVCExceptionalHandlerExample”

Maven dependencies

2) Our pom.xml will look like below

pom.xml


  4.0.0
  com.arpit.java2blog
  SpringRestfulWebServicesWithJSONExample
  war
  0.0.1-SNAPSHOT
  SpringRestfulWebServicesWithJSONExample Maven Webapp
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
    
   javax.servlet
   javax.servlet-api
   3.1.0
  

  
   org.springframework
   spring-core
   ${spring.version}
  
  
   org.springframework
   spring-webmvc
   ${spring.version}
  
   
            com.fasterxml.jackson.core
            jackson-databind
             2.4.1
        
 
 
  SpringRestfulWebServicesWithJSONExample

  
   
    org.apache.maven.plugins
    maven-compiler-plugin
    3.1
    
     ${jdk.version}
     ${jdk.version}
    
   
  

 
 
  4.2.1.RELEASE
  1.7
 

Spring application configuration:

3) Change web.xml as below:



 Archetype Created Web Application
  
   index.jsp

  
 
 springrest
 
  org.springframework.web.servlet.DispatcherServlet
 
 1



 springrest
 /


4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.



 

 
  
   /WEB-INF/
  
  
   .jsp
  
 
 

Create Controller

6) Create a controller named “HelloWorldController.java” in package org.arpit.java2blog.controller

package org.arpit.java2blog.controller;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.arpit.java2blog.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

    private static final Logger logger = Logger
            .getLogger(HelloWorldController.class);

    @RequestMapping("/helloworld/{helloType}")
    public ModelAndView hello(@PathVariable("helloType") String helloType)
            throws CustomException, IOException {

        String helloWorldMessage="";
        if (helloType.equalsIgnoreCase("CustomException")) {
            throw new CustomException("Custom exception occured");
        } else if (helloType.equalsIgnoreCase("IOException")) {
            throw new IOException(" IO exception occured");
        } else {
            helloWorldMessage = "Hello world from java2blog!";

        }

        return new ModelAndView("hello", "message", helloWorldMessage);
    }

    @ExceptionHandler(CustomException.class)
    public ModelAndView catchCustomException(CustomException ex) {

        ModelAndView model = new ModelAndView("Custom_Exception");
        model.addObject("errorMessage", ex.getMessage());
        return model;
    }

    @ExceptionHandler(IOException.class)
    public ModelAndView catchIOException(IOException ex) {

        ModelAndView model = new ModelAndView("IOException");
        model.addObject("errorMessage", ex.getMessage());
        return model;
    }
}

Create view

As you can see, we have annotated two method i.e. catchCustomException and catchIOException with @ExceptionHandler. These methods will handle CustomException and IOException respectively.

Modify index.jsp as below

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




HelloWorld


Hello World!!

Create Custom_Excepion.jsp in /WEB-INF/ folder to handle CustomException exception.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Custom Exception


${errorMessage}

Create IOException.jsp in /WEB-INF folder as below to handle IOException.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




IO Exception


${errorMessage}

7) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

Maven build in eclipse
8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

10) Lets hit below URL
http://localhost:8080/SpringMVCExceptionalHandlerExample/helloworld/hello


As you can see, it is working fine with above URL.
Now lets hit some URL which will throw exception and exception will be handled by @ExcpetionHandler.

When you hit below URL.
http://localhost:8080/SpringMVCExceptionalHandlerExample/helloworld/CustomException



As you can see, when you hit above URL , CustomException is thrown and handled by catchCustomException method.

When you hit below URL.
http://localhost:8080/SpringMVCExceptionalHandlerExample/helloworld/IOException


As you can see, when you hit above URL , CustomException is thrown and handled by catchIOException method.
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.