Spring MVC Exception Handling using @ControllerAdvice annotation

error-spring-mvc-exception

Spring MVC provides a great way to handle exceptions and errors. @ExceptionHandler annotation is core to this feature. For each Spring controller we can simply define a method that automatically gets called if a given exception occurs. For example:

import org.springframework.web.bind.annotation.ExceptionHandler;

//..
@ExceptionHandler(IOException.class)
public String exception(Exception e) {
		
	//..
	return "error";
}

Thus whenever an IOException is raised from any controller method will call the above method exception(). We mapped IOException.class to this method using @ExceptionHandler annotation.

One short coming of this annotation is that it only handles exception getting raised from the controller where it is defined. It will not handle exceptions getting raised from other controllers. However this is a way to overcome this problem. @ControllerAdvice annotation is at your service for that.

@ControllerAdvice annotation

This annotation is used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods.


import org.springframework.web.bind.annotation.ControllerAdvice;
//..
@ControllerAdvice
public class ExceptionControllerAdvice {

	@ExceptionHandler(Exception.class)
	public String exception(Exception e) {

		return "error";
	}
}

Thus if we define our @ExceptionHandler annotation on method in @ControllerAdvice class, it will be applied to all the controllers.

One thing worth noting here is that Spring configuration must define mvc namespace in order to identify @ControllerAdvice annotation. Thus you must define following in your spring-servlet.xml file.

	 

If you have defined just the it wouldn’t work. The @ControllerAdvice will simply wont be loaded. So always remember to use in Spring configuration.

Let us check a complete tutorial.

Complete Tutorial

Now we know the concept, let us use it and create a Spring MVC based application to track page hits. We will use Cookie to track page hit counter.
For this tutorial I will be using following tools and technologies:

  1. Spring MVC 3.2.6.RELEASE
  2. Java 6
  3. Eclipse
  4. Maven 3

Following is the project structure.
spring-exception-handling-project-structure
Create and copy following file contents in the project structure.

Maven configuration: pom.xml


	4.0.0
	net.viralpatel.spring
	Spring_ExceptionHandler_example
	war
	1.0.0-SNAPSHOT
	Spring_ExceptionHandler_example
	
		3.2.6.RELEASE
		UTF-8
		1.6
	
	
		
			javax.servlet
			servlet-api
			2.5
			provided
		
		
		
			org.springframework
			spring-web
			${org.springframework.version}
		
		
			org.springframework
			spring-webmvc
			${org.springframework.version}
		
		
		
			taglibs
			standard
			1.1.2
		
		
			javax.servlet
			jstl
			1.1.2
		
	
	
		Spring_ExceptionHandler_example
	
	
	

Maven configuration is simple. We just need Spring MVC and JSTL dependency.

Deployment description: web.xml



	Spring MVC Http Cookie
	
		hello.htm
	
	
		spring
		org.springframework.web.servlet.DispatcherServlet
		1
	
	
		spring
		*.htm
	

Web.xml is quite simple too. We just need to configure Spring’s DispatcherServlet with *.htm url pattern.

Spring configuration: spring-servlet.xml




	 

	


	
		
		
		
	
	

In spring-servlet.xml we just defined component scan to load @Controller classes. Also we defined a view resolver that will points to JSPs within /WEB-INF/jsp/ folder. As noted earlier, we defined to load @ControllerAdvice classes.

Spring Controller

We will define one spring controller and one @ControllerAdvice class for this example. One is just to render a hello page with a link. On click of the link we invoke another controller method. This method however will throw an exception.

HelloController.java

package net.viralpatel.spring;

import java.io.IOException;

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

@Controller
public class HelloController {

	@RequestMapping(value = "/hello.htm")
	public String hello() throws IOException {
		
		// render hello.jsp page
		return "hello";
	}


	@RequestMapping(value = "/test.htm")
	public String test() throws IOException {
		
		//just throw exception to test the exceptionhandler mapping
		if(true) {
			throw new IOException("this is io exception");
		}
		
		// render hello.jsp page
		return "hello";
	}
}

ExceptionControllerAdvice.java

package net.viralpatel.spring;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class ExceptionControllerAdvice {

	@ExceptionHandler(Exception.class)
	public ModelAndView exception(Exception e) {
		
		ModelAndView mav = new ModelAndView("exception");
		mav.addObject("name", e.getClass().getSimpleName());
		mav.addObject("message", e.getMessage());

		return mav;
	}
}

This class simply define a @ControllerAdvice and a method with @ExceptionHandler. This method will be called whenever an unhandled exception occurs.

JSP views

Two JSPs will be used. One for hello page and one which will be called in case of any error.

hello.jsp



	Spring MVC Exception Handling	



	

Spring MVC Exception Handling

Click here to test Exception handling

exception.jsp



	Spring MVC @ControllerAdvice example	



	

Ops! Something went wrong

${name}: ${message}

Demo

Compile and run the project. Open your favorite web browser and point to below URL:

http://localhost:8080/Spring_ExceptionHandler_example/hello.htm

spring-mvc-exception-handling-controlleradvice-demo

Once you click the link, the controller throws an exception which is handled nicely by @ExecptionHandler method.

spring-mvc-exception-handling-controlleradvice-demo2

Download Source Code

Spring_ExceptionHandler_example.zip (10 KB)



5 Comments

  • sreenath 13 March, 2014, 11:50

    Hi,
    Thanks for writing this tutorial.
    I am getting below exception while running my spring application, can guide me if i am doing anything wrong.
    org.xml.sax.SAXParseException: cos-all-limited.1.2: An ”all” model group must appear in a particle with ‘{‘min occurs’}’='{‘max occurs’}’=1, and that particle must be part of a pair which constitutes the ‘{‘content type’}’ of a complex type definition.
    at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:267)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:201)
    =====================
    below is my config file

  • Sarala Rajagopalan 14 May, 2014, 23:29

    Nicely complements this other useful blog post: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

  • Gautham 4 July, 2014, 13:15

    Hi,

    I have done the setup but unfortunately my @ControllerAdvice Class is not handling the exceptions.
    I have a similar situation like below link.

    http://stackoverflow.com/questions/21884737/controlleradvice-not-firing

    Any help would be appreciated.

  • priya 4 August, 2014, 12:38

    please post a clear example on freemarker+springMVC with freemarker TemplateExceptionHandler.

    How to catch TemplateException raised in freemarker???

  • sandy 10 September, 2014, 22:00

    Hi,

    Nice example, Can i forward the exception message to the same jsp page instead of a seperate exception page ? If it is possible please let me know the way to do it.

    Thanks

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]