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:
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" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">/error/500</prop> </props> </property> </bean>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" 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>Spring MVC Minimal</title> </head> <body> <b>Sorry</b> <p>There was a failure. </p> </body> </html>I modfied the controller to just throw an exception:
public class DataWelcomeController { @RequestMapping(value = { "/anything.do" }) 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