Home » Enterprise Java » spring » MVC » Spring MVC @ExceptionHandler Annotation Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Spring MVC @ExceptionHandler Annotation Example

In this post, we feature a comprehensive Example on Spring MVC @ExceptionHandler Annotation. Unexpected exceptions or errors can be thrown anytime during the execution of a program. Spring MVC framework provides three different approaches for handling the exceptions i.e.

  • Using XML based configuration by declaring the SimpleMappingExceptionResolver bean in the Spring’s application context file and mapping the exception types with the respective view-names
  • Using the @ControllerAdvice annotation for annotating any class to define the global exception handler
  • Using the @ExceptionHandler annotation for annotating the method(s) to handle the exceptions raised by the Spring controller methods

In this tutorial, we will show how to do the exception handling in Spring MVC framework by using the @ExceptionHandler annotation.

1. Introduction

1.1 Spring Framework

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web-services

1.2 Spring Mvc Framework

Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a POJO class which encapsulates the application data given by the controller
  • View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the JSP templates written with Java Standard Tag Library (JSTL)
  • Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
Spring MVC @ExceptionHandler Annotation - MVC Overview

Fig. 1: Model View Controller (MVC) Overview

Now, open up the Eclipse IDE and let’s see how to implement the @ExceptionHandler annotation in the spring mvc framework!

2. Spring MVC @ExceptionHandler Annotation Example

Here is a step-by-step guide for implementing this tutorial in the spring mvc framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring MVC @ExceptionHandler Annotation - Application Project Structure

Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring MVC @ExceptionHandler Annotation - Create a Maven Project

Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Spring MVC @ExceptionHandler Annotation - Project Details

Fig. 4: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring MVC @ExceptionHandler Annotation - Archetype Selection

Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring MVC @ExceptionHandler Annotation - Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring.mvc</groupId>
	<artifactId>SpringMvcExceptionHandlerAnnotation</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Servlet API, Spring Mvc etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring mvc framework. The rest dependencies such as Spring Beans, Spring Core etc. will be automatically resolved by Maven. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring.mvc</groupId>
	<artifactId>SpringMvcExceptionHandlerAnnotation</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMvcExceptionHandlerAnnotation Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<!-- Servlet API Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.8.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMvcExceptionHandlerAnnotation</finalName>
	</build>
</project>

3.2 Configuration Files

Let’s write all the configuration files involved in this application.

3.2.1 Web Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>SpringMvcExceptionHandler</display-name>

	<servlet>
		<servlet-name>exceptionhandlerdispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>exceptionhandlerdispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

3.2.2 Spring Configuration File

To configure the spring framework, developers need to implement a bean configuration file i.e. exceptionhandlerdispatcher-servlet.xml which provide an interface between the basic Java class and the outside world. Add the following code to it:

exceptionhandlerdispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:component-scan base-package="com.spring.mvc.demo" />
	<context:component-scan base-package="com.spring.mvc.demo.exception" />

	<context:annotation-config />

	<!-- For resolving the view name and invoking the particular view page for 
		the user -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

Do note:

  • This file is loaded by the spring’s Dispatcher Servlet which receives all the requests coming into the application and dispatches them to the controller for processing
  • This file has the InternalResourceViewResolver bean declaration that tells the framework how to find the physical JSP files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name

3.3 Java Class Creation

Let’s write the Java classes involved in this application.

3.3.1 Custom Exception Class

Let’s create a simple custom exception class. In this class, we have defined the “error code” and “error message” member variables for specifying the user-defined error messages. Add the following code to it:

MyException.java

package com.spring.mvc.demo.exception;

import org.springframework.stereotype.Component;

@Component
public class MyException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	private String errCode;
	private String errMsg;

	public MyException() { }

	public MyException(String errCode, String errMsg) {
		this.errCode = errCode;
		this.errMsg = errMsg;
	}

	public String getErrCode() {
		return errCode;
	}

	public void setErrCode(String errCode) {
		this.errCode = errCode;
	}

	public String getErrMsg() {
		return errMsg;
	}

	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}	
}

3.3.2 Controller Class

Let’s create a simple class where the @Controller annotation specifies this class as a spring controller and is responsible for handling the incoming requests. The @ExceptionHandler annotation is used to annotate the method(s) in the controller class for handling the exceptions raised during the execution of the controller methods. In here:

  • If the user provides a /error request, it throws the MyException, and the handleMyException() method will be invoked
  • If the user provides a /io-error request, it throws the IOException, and the handleException() method will be invoked

Using the @ExceptionHandler annotation is easy as it allows developers to do some processing before returning to the error view. This annotation also allows specifying a list of exception classes i.e.

Snippet

@ExceptionHandler({IOException.class, SQLException.class})
public ModelAndView handleException(Exception ex) {

	ModelAndView model = new ModelAndView();	 
	model.addObject("exception", ex.getMessage());
	model.setViewName("error/my_error");

	return model;
}

This snippet method will be invoked if the exception thrown by the controller method is one of the types (or subtypes) in the given list. Add the following code to the ExceptionCtrl.java class:

ExceptionCtrl.java

package com.spring.mvc.demo;

import java.io.IOException;

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.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.spring.mvc.demo.exception.MyException;

@Controller
public class ExceptionCtrl {

	@RequestMapping(value= "/exception/{type}", method= RequestMethod.GET)
	public String exception(@PathVariable(name="type") String exception) throws IOException {

		if (exception.equalsIgnoreCase("error")) {			
			throw new MyException("A1001", "This is a custom exception message.");
		} else if (exception.equalsIgnoreCase("io-error")) {			
			throw new IOException();
		} else {
			return "success";
		}
	}

	@ExceptionHandler(MyException.class)
	public ModelAndView handleMyException(MyException mex) {

		ModelAndView model = new ModelAndView();
		model.addObject("errCode", mex.getErrCode());
		model.addObject("errMsg", mex.getErrMsg());
		model.setViewName("error/generic_error");
		return model;
	}

	@ExceptionHandler(Exception.class)
	public ModelAndView handleException(Exception ex) {

		ModelAndView model = new ModelAndView();
		model.addObject("errMsg", "This is a 'Exception.class' message.");
		model.setViewName("error/generic_error");
		return model;

	}
}

3.4 Index View

It’s time to create the index page of the tutorial that will invoke the controller method on the user click. So let us write a simple result view in SpringMvcExceptionHandlerAnnotation/src/main/webapp/ folder. Add the following code to it:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <title>Index</title>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
	</head>
	<body>
	    <div class="container">
	        <h2 align="center" class="text-primary">Spring MVC @ExceptionHandler Example</h2>
	        <hr />
	
	        <div id="errlinks">
	            <span id="errlink1">
			    	<a href="<%=request.getContextPath() %>/exception/error" class="btn btn-default">Error</a>
			    </span>
	            <div> </div>
	            <span id="errlink2">
			    	<a href="<%=request.getContextPath() %>/exception/io-error" class="btn btn-default">I/O Error</a>
			    </span>
	        </div>
	    </div>
	</body>
</html>

3.5 JSP View

Spring Mvc supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write a simple result view in SpringMvcExceptionHandlerAnnotation/src/main/webapp/WEB-INF/views/error/ folder.

3.5.1 Error Page

This is the output page of the tutorial which will display the error code and messages based on the exception that occurs in the controller methods. Add the following code to it:

generic_error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <title>Exception</title>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
	</head>
	<body>
	    <div class="container">
	        <h2 align="center" class="text-primary">Spring MVC @ExceptionHandler Example</h2>
	        <hr />
	
	        <!-- Error Code -->
	        <div id="errorcode">
	            <c:if test="${not empty errCode}">
	                <h3 class="text-info">${errCode} : My Error</h3>
	            </c:if>
	            <c:if test="${empty errCode}">
	                <h3 class="text-info">Input/Output Error</h3>
	            </c:if>
	        </div>
	
	        <!-- Error Message -->
	        <div id="errormessage">
	            <c:if test="${not empty errMsg}">
	                <h4 class="text-danger">${errMsg}</h4>
	            </c:if>
	        </div>
	    </div>
	</body>
</html>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Spring MVC @ExceptionHandler Annotation - Deploy Application on Tomcat

Fig. 7: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL to display the application’s index page.

http://localhost:8082/SpringMvcExceptionHandlerAnnotation/

Server name (localhost) and port (8082) may vary as per your tomcat configuration.

Spring MVC @ExceptionHandler Annotation - Index page

Fig. 8: Index page

A user can click on the Error link to display the custom exception message as shown in Fig. 9.

Spring MVC @ExceptionHandler Annotation - Custom exception message

Fig. 9: Custom exception message

A user can click on the I/O Error link to display the IO exception message as shown in Fig. 10.

Spring MVC @ExceptionHandler Annotation - I/O exception message

Fig. 10: I/O exception message

That’s all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and don’t forget to share!

6. Conclusion

In this section, developers learned how to implement the @ExceptionHandler annotation in the spring mvc framework. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Spring MVC @ExceptionHandler Annotation

Download
You can download the full source code of this example here: SpringMvcExceptionHandlerAnnotation
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of