Search This Blog

Wednesday, 12 December 2012

Handling exceptions in Spring MVC

Exceptions occur. And when they occur in a web application, it leaves us developers looking very stupid. An Apache Tomcat page showing a stack trace and 500 in bold words makes it even worse for us. Graceful handling of exceptions in a web application makes things a tad better.
Spring provides us with a clean way of redirecting application flow to an error page when an exception occurs.
For this we need to add the bean to our xml configuration:
<bean id="exceptionResolver"
    <property name="exceptionMappings">
            <prop key="java.lang.Exception">/error/500</prop>
The bean includes a properties object which holds a collection of Exceptions and view names. If a controller throws an exception the error page will be displayed. As we use an InternalResourceViewResolver the flow will move to jsp/error/500.jsp page.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Spring MVC Minimal</title>
        <p>There was a failure. </p>
I modfied the controller to just throw an exception:
public class DataWelcomeController {

    @RequestMapping(value = { "/" })
    public String handleRequest(final HttpServletRequest request,
            final HttpServletResponse response, Map<String, Object> model,
            @RequestParam("shva") int val) throws Exception {
        throw new Exception();
On execution the error page is displayed:

No comments:

Post a Comment