Exception Handling in Spring

In Web Application, when any kind exception or error comes it should be handled and displayed with user-friendly message.
Very basically we can have error page, and we can configure those pages for particular HTTP Error Codes in web.xml file.

For Example-

<error-page>
  <error-code>500</error-code>
  <location>/WEB-INF/pages/internal_server_error.jsp</location>
</error-page>

Now, you can have a question- Why Exception Handling with Spring?

-What happened in above case, we are displaying error page without any Custom Message, we are showing static page.
Also when any error comes, it will be very helpful if we get chance to log it.
So, both of these problem solved with Spring, You can have custom and user-friendly message for exception.


Ways of Handling Exception

1. SimpleMappingExceptionResolver
2. Annotation Based using @ExceptionHandler

1.SimpleMappingExceptionResolver

We are creating one POJO for Custom Exception.

public class CustomException extends RuntimeException{
	
	public String customMsg;

	public String getCustomMsg() {
		return customMsg;
	}

	public void setCustomMsg(String customMsg) {
		this.customMsg = customMsg;
	}

	public CustomException(String customMsg) {
		this.customMsg = customMsg;
	}
	
}




Now we will have one sample class which is throwing the newly created exception-

public class CustomerController 
{
@Override
    protected ModelAndView sampleMethodThrowingException(HttpServletRequest request, HttpServletResponse  response) throws Exception 
   {
    throw new CustomException("Throwing Generic Exception: System Error");
   }
}

Spring Configuration:
Writing a bean with SimpleMappingExceptionResolver.
When CustomException is thrown it should go to error.jsp.

<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
   <property name="exceptionMappings">
   	<props>
     		<prop key="com.spring.common.exception.CustomException">
         GenericExceptionPage
     		</prop>
     		<prop key="java.lang.Exception">error</prop>
   	</props>
   </property>
</bean>

error.jsp:
Error page to render Model Object Populated when Exception is thrown.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<body>
<h1>Hi.......${exception.customMsg}</h1>
</body>
</html>


2. Annotation based @ExceptionHandler

Here I have thrown some exception in Controller class and thrown exception are handled with @ExceptionHandler(<ExceptionType>.class)

@RequestMapping(value = "/exception1")
public String exception1()
{
throw new NullPointerException("Exception1 as plain text with <strong>html</strong> tags");
}
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public String handleException1(NullPointerException ex)
{return ex.getMessage();}

@RequestMapping(value = "/exception2", method = RequestMethod.GET)
public String exception2()
{
throw new IndexOutOfBoundsException();
}
@ExceptionHandler(IndexOutOfBoundsException.class)
public String handleException2(IndexOutOfBoundsException ex)
{
return "error";
}

@RequestMapping(value = "/exception3", method = RequestMethod.GET)
public String exception3()
{
throw new IllegalStateException("Exception3 with response status");
}
@ExceptionHandler(IllegalStateException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "exception3")
public ModelAndView handleException3(IllegalStateException ex,HttpServletResponse response) throws IOException
{
return new ModelAndView();
}

Returning to custom error page with custom message

@RequestMapping(value = "/exception5")
public String exception5()
{
throw new GenericException("This is Custom Exception Handler");
}

@ExceptionHandler(GenericException.class)
public ModelAndView handleException5(GenericException ex)
{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("ex", ex);
        return modelAndView;
}

Corresponding error page:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<body>
<h1>Hi.......${ex.customMsg}</h1>
</body>
</html>

When we set view name in Model Object, we expect to fetch proper .jsp page, so our code should have mapping bean-

<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s