Controller based ExceptionHandler & Global ExceptionHandler

Controller based ExceptionHandler

In this type of Exception handling, we can write handler methods inside the controller class itself.
So to achive this , we need to
a) Define a new method inside the controller
b) Annotate this mehod with @ExceptionHandler and parameter as Exception that we have to handle
c) Handle the Exception inside this method and return the specific view or JSON based on the requirement.

Limitation of this approach is that , only those exceptions which are thrown inside this controller class can be handled.

Any exceptions thrown from outside this controller class will be left unhandled and same exception stack trace will appear in the UI in that case.

We can define as many handler methods as we want with each exception.

But specific exception handled methods will be given highest priority.

So if there are 2 exception handler methods ,method 1 is handling NullPointerException and method 2 is handling Exception , now if Null pointer exception is thrown then method 1 handler will be executed.

We will see below how this can be implemented.

Global ExceptionHandler
In this approach , the implementation is almost similar to @ExceptionHandler approach only.
The only difference here is that , it can handle all the exceptions thrown from any of the controllers in the application.

So it is always advisable to use over second approach.

It can be implemented as
a) Define a new class and anootate this class with @ControllerAdvice
b) Keep on adding new method for each exception using @ExceptionHandler annotation.

So class which is annotated with @ControllerAdvice is considered as global exception handler because methods inside it can handle the exception thrown from any controller in the application.

Lets see the real time example

Define a controller with @ExceptionHandler annotation

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import org.springframework.web.bind.annotation.ModelAttribute;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9.  
  10. import com.kb.exception.InvalidUserException;
  11. import com.kb.model.User;
  12.  
  13. @Controller
  14. public class LoginController {
  15.  
  16.     @RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
  17.     public String displayLoginPage(Model model){
  18.         User user = new User();
  19.         model.addAttribute("user", user);
  20.         return "/login";
  21.     }
  22.    
  23.     @RequestMapping(value="/doLogin",method=RequestMethod.POST)
  24.     public String doLogin(@ModelAttribute User user,Model model){
  25.        
  26.         String userName=user.getUserName();
  27.         String password = user.getPassword();
  28.         if("kb".equals(userName) && "1234".equals(password)){
  29.             model.addAttribute("user", user);
  30.             return "/home";
  31.         }
  32.         else{
  33.             //Log the exception
  34.             throw new InvalidUserException("INVALID_USER","User is not Valid for this site");
  35.         }
  36.        
  37.     }
  38.    
  39.     @RequestMapping(value="/getGenericException",method=RequestMethod.GET)
  40.     public String getGenericException(){
  41.  
  42.         throw new Exception();
  43.     }
  44.    
  45. @ExceptionHandler(InvalidUserException.class)
  46.     public String handleInvalidUserException(){
  47.  
  48.         return "userNotFound";
  49.     }  
  50. }
package com.kb.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.exception.InvalidUserException;
import com.kb.model.User;

@Controller
public class LoginController {

	@RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
	public String displayLoginPage(Model model){
		User user = new User();
		model.addAttribute("user", user);
		return "/login";
	}
	
	@RequestMapping(value="/doLogin",method=RequestMethod.POST)
	public String doLogin(@ModelAttribute User user,Model model){
		
		String userName=user.getUserName();
		String password = user.getPassword();
		if("kb".equals(userName) && "1234".equals(password)){
			model.addAttribute("user", user);
			return "/home";
		}
		else{
			//Log the exception
			throw new InvalidUserException("INVALID_USER","User is not Valid for this site");
		}
		
	}
	
	@RequestMapping(value="/getGenericException",method=RequestMethod.GET)
	public String getGenericException(){

		throw new Exception();
	}
	
@ExceptionHandler(InvalidUserException.class)
	public String handleInvalidUserException(){

		return "userNotFound";
	}	
}

This controller is a login controller which is having a request mapping for login page.
We have added a method called handleInvalidUserException just to show how the exception can be handled by a method using @ExceptionHandler.

Define a controller with @ControllerAdvice annotation

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.ControllerAdvice;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6.  
  7. @ControllerAdvice
  8. public class ExceptionHandlerController {
  9.  
  10.         @ExceptionHandler(Exception.class)
  11.     public String handleGenericException(){
  12.  
  13.         return "genericError";
  14.     }}
  15.  
package com.kb.controllers;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ExceptionHandlerController {

		@ExceptionHandler(Exception.class)
	public String handleGenericException(){

		return "genericError";
	}}
 

In this controller we have written an handler method for general Exception.

This handler handles all the exceptions thrown from any controller in the application.

So we are throwing an exception from Login controller and its getting handled by this method.

Create the view page for exception handling

userNotFound.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2> Sorry, some technical error, Please try again</h2>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2> Sorry, some technical error, Please try again</h2>
</body>
</html>

genericError.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2> Sorry, some technical error, Please try again</h2>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2> Sorry, some technical error, Please try again</h2>
</body>
</html>

Create the view page for login and home page
login.jsp

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  2. <html>
  3. <head>
  4. <title>Spring MVC Exception Handling</title>
  5. </head>
  6.  
  7. <body>
  8.     <h2>Enter below details to Login</h2>
  9.  
  10.     <form:form method="POST" modelAttribute="user" action="doLogin">
  11.         <table>
  12.            
  13.             <tr>
  14.                 <td>Enter your User Name</td>
  15.                 <td><form:input path="userName" /></td>
  16.             </tr>
  17.            
  18.             <tr>
  19.                 <td>Enter your password:</td>
  20.                 <td><form:password path="password"  showPassword="true"/></td>
  21.             </tr>
  22.            
  23.             <tr>
  24.                 <td><input type="submit" name="submit" value="Click here to Login"></td>
  25.             </tr>
  26.         </table>
  27.     </form:form>
  28.  
  29. </body>
  30. </html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>

<body>
	<h2>Enter below details to Login</h2>

	<form:form method="POST" modelAttribute="user" action="doLogin">
		<table>
			
			<tr>
				<td>Enter your User Name</td>
				<td><form:input path="userName" /></td>
			</tr>
			
			<tr>
				<td>Enter your password:</td>
				<td><form:password path="password"  showPassword="true"/></td>
			</tr>
			
			<tr>
				<td><input type="submit" name="submit" value="Click here to Login"></td>
			</tr>
		</table>
	</form:form>

</body>
</html>

home.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Login Success</title>
  9. </head>
  10. <body>
  11.  <div align="center">
  12.         <h2>Welcome ${user.userName}! You have been successfully Logged in.</h2>
  13.   </div>
  14. </body>
  15. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Success</title>
</head>
<body>
 <div align="center">
        <h2>Welcome ${user.userName}! You have been successfully Logged in.</h2>
  </div>
</body>
</html>

Create the model class

  1. package com.kb.model;
  2.  
  3. public class User {
  4.  
  5.     private String userName;
  6.  
  7.     private String password;
  8.  
  9.     public String getUserName() {
  10.         return userName;
  11.     }
  12.  
  13.     public void setUserName(String userName) {
  14.         this.userName = userName;
  15.     }
  16.  
  17.     public String getPassword() {
  18.         return password;
  19.     }
  20.  
  21.     public void setPassword(String password) {
  22.         this.password = password;
  23.     }
  24.  
  25. }
package com.kb.model;

public class User {

	private String userName;

	private String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

Create spring configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.      
  16.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17.         <property name="prefix" value="/WEB-INF/pages/" />
  18.         <property name="suffix" value=".jsp" />
  19.     </bean>
  20.    
  21. </beans>
<?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:p="http://www.springframework.org/schema/p"
    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-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:component-scan base-package="com.kb.*" />
    <mvc:annotation-driven />
     
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
	
</beans>

Create the web.xml

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Controller Advice Example</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.  
  28.     <!-- Loads Spring Security configuration file -->
  29.      <context-param>
  30.         <param-name>contextConfigLocation</param-name>
  31.         <param-value>
  32.             /WEB-INF/spring-mvc.xml,
  33.         </param-value>
  34.     </context-param>
  35. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Controller Advice Example</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Loads Spring Security configuration file -->
	 <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
	</context-param>
</web-app>

Create the pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>ControllerAdviceExample</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>ControllerAdviceExample Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47.   </dependencies>
  48.   <build>
  49.     <finalName>ControllerAdviceExample</finalName>
  50.     <plugins>
  51.             <plugin>
  52.                 <groupId>org.apache.maven.plugins</groupId>
  53.                 <artifactId>maven-compiler-plugin</artifactId>
  54.                 <version>2.5.1</version>
  55.                 <configuration>
  56.                     <source>1.8</source>
  57.                     <target>1.8</target>
  58.                 </configuration>
  59.             </plugin>
  60.         </plugins>
  61.   </build>
  62. </project>
<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>Spring</groupId>
  <artifactId>ControllerAdviceExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ControllerAdviceExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
  </dependencies>
  <build>
    <finalName>ControllerAdviceExample</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

Lets build and deploy the application.

Access below url

http://localhost:8080/ControllerAdviceExample/displayLoginPage

Now enter invalid credentials as below

See the below output which comes from the userNotFound.jsp

This exception is thrown in the login controller and handled by the handleInvalidUserException method and returns the userNotFound view as above.

Now access the below url
http://localhost:8080/ControllerAdviceExample/getGenericException

This url calls the method getGenericException in the login controller and we are intentionally throwing the exception in this method.

This exception is not handled in the login controller but it is handled inside a separate controller called ExceptionHandlerController which returns the genericError jsp page.

Like this, exception thrown from any controller can be handled from a @Controlleradvice controller.

Download this project ControllerAdviceExample.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on