Announcement Announcement Module
Collapse
No announcement yet.
Example of ExceptionHandler Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Example of ExceptionHandler

    I need some example of ExceptionHandlerResolver implementation and his declaration in the application context plz.

    Thanks.

  • #2
    The following example uses a dummy Controller that throws unchecked Exceptions (ArrayStoreException, ArithmeticException) depending on the value of the parameter "class"

    1. SpringController:
    Code:
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.mvc.Controller;
    import org.springframework.web.servlet.ModelAndView;
    
    public class SpringController implements Controller {
    
      public ModelAndView handleRequest(HttpServletRequest request,
                                        HttpServletResponse response)
                throws ServletException, IOException {
    
        if ("arraystore".equals(request.getParameter("class")))
          throw new ArrayStoreException();
        else
          throw new ArithmeticException();
      }
    }
    2. ArrayStoreExceptionHandler handles ArrayStoreException:
    Code:
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.core.Ordered;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    
    public class ArrayStoreExceptionHandler implements HandlerExceptionResolver, Ordered {
      private int order;
    
      public ModelAndView resolveException(HttpServletRequest request,
                                           HttpServletResponse response,
                                           Object handler,
                                           Exception e) {
        if (e instanceof ArrayStoreException)
          return new ModelAndView("arraystoreView");
        else
          return null;
      }
    
      public int getOrder() {
        return order;
      }
    
      public void setOrder(int order) {
        this.order = order;
      }
    }
    3. ArithmeticExceptionHandler (very simillar) handles ArithmeticException:
    Code:
      ...
        if (e instanceof ArithmeticException)
          return new ModelAndView("arithmeticView");
        else
          return null;
      ...
    4. spring-servlet.xml putting it all together:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
     "http&#58;//www.springframework.org/dtd/spring-beans.dtd">
    
    <beans>
      <bean id="springController" class="SpringController"/>
    
      <bean id="handler1" class="ArithmeticExceptionHandler">
        <property name="order"><value>1</value></property>
      </bean>
    
      <bean id="handler2" class="ArrayStoreExceptionHandler">
        <property name="order"><value>2</value></property>
      </bean>
    
      <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
          <props>
            <prop key="/exception.htm">springController</prop>
          </props>
        </property>
      </bean>
    
      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
          <value>org.springframework.web.servlet.view.InternalResourceView</value>
        </property>
        <property name="prefix"><value>/</value></property>
        <property name="suffix"><value>.html</value></property>
      </bean>
    </beans>
    5. web.xml:
    Code:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
               "http&#58;//java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    
      <display-name>Forums</display-name>
      <description>Forums demo web application</description>
    
      <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.htm</url-pattern>
      </servlet-mapping>
    
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
      </welcome-file-list>
    </web-app>
    6. index.html:
    Code:
    <html>
    <head>
     <title>Exception Handler</title>
    </head>
    <body>
     <a href="exception.htm?class=arraystore">ArrayStoreExceptionHandler</a><br>
     <a href="exception.htm?class=arithmetic">ArithmeticExceptionHandler</a>
    </body>
    </html>
    7. arraystoreView.html:
    Code:
    <html>
    <head>
     <title>Exception Handler</title>
    </head>
    <body>
     ArrayStoreExceptionHandler called!!!
    </body>
    </html>
    7. arithmeticView.html:
    Code:
    <html>
    <head>
     <title>Exception Handler</title>
    </head>
    <body>
     ArithmeticExceptionHandler called!!!
    </body>
    </html>
    8. How does it work?
    When DispatchServlet is instanciated by the web container, it calls
    Code:
    	private void initHandlerExceptionResolvers&#40;&#41; throws BeansException &#123;
    		this.handlerExceptionResolvers = new ArrayList&#40;&#41;;
    		if &#40;this.detectAllHandlerExceptionResolvers&#41; &#123;
    			// find all HandlerExceptionResolvers in the ApplicationContext
    			Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors&#40;
    					getWebApplicationContext&#40;&#41;, HandlerExceptionResolver.class, true, false&#41;;
    			this.handlerExceptionResolvers = new ArrayList&#40;matchingBeans.values&#40;&#41;&#41;;
    			// we keep HandlerExceptionResolvers in sorted order
    			Collections.sort&#40;this.handlerExceptionResolvers, new OrderComparator&#40;&#41;&#41;;
    		&#125;
    		else &#123;
    			try &#123;
    				Object her = getWebApplicationContext&#40;&#41;.getBean&#40;HANDLER_EXCEPTION_RESOLVER_BEAN_NAME&#41;;
    				this.handlerExceptionResolvers.add&#40;her&#41;;
    			&#125;
    			catch &#40;NoSuchBeanDefinitionException ex&#41; &#123;
    				// ignore, no HandlerExceptionResolver is fine too
    			&#125;
    		&#125;
    	&#125;
    DispatchServlet is then aware of ArrayStoreExceptionHandler and ArithmeticExceptionHandler and knows in whitch order they should be called.

    Question
    :?: I do not know if it is a good idea to paste a lot of code!! does phpB supports attachments?

    Comment


    • #3
      Originally posted by irbouho
      I do not know if it is a good idea to paste a lot of code!! does phpB supports attachments?
      Posting code here is fine I think if it answers the specific question. If it's more generally useful, like this, then a Confluence page would be an idea - you could post the link to it in your reply.

      BTW - were you advocating creating separate exception resolvers for each type of exception or did I misunderstand something..?

      Comment


      • #4
        BTW - were you advocating creating separate exception resolvers for each type of exception or did I misunderstand something..?
        No, I do not advocate it. I was just trying to show that Spring supports more than one HandlerExceptionResolver.

        Comment


        • #5
          I didn't knew the automagically way spring resolve HandlerExceptiosResolver implementation, now iam a happy user again...

          Thanks irbouho...

          Comment

          Working...
          X