Catching exceptions in a declarative way....

Discussions

Web tier: servlets, JSP, Web frameworks: Catching exceptions in a declarative way....

  1. Hi all,
    I'd like to catch my exceptions as declared in my web.xml file

    <error-page>
    <exception-type>javax.servlet.ServletException</exception-type>
    <location>/error.jsp</location>
    </error-page>

    the problem is that this approach doesn't work with servlets:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    .......

    throw new javax.servlet.ServletException("errore");

    }

    this doesn't redirect to error.jsp, but it simply crashes the navigation with the stack trace.

    On the other hand with JSP...
    <%
    throw new javax.servlet.ServletException("errore da jsp");
    %>

    it works. I'm using Tomcat 4.1 container.
    Any help ???
    Thanks
    Francesco
  2. Maybe you should take a look at the 1.1 release of the Struts-Framework (still in beta). The new release does support declarative Exception-Handling as far as I know.
    Visit: http://jakarta.apache.org/struts/index.html
  3. Take a look at the Chapter 10 draft of my Struts book available on this site at:

    http://www.theserverside.com/resources/strutsreview.jsp

    It covers the declarative exception handling available in Struts 1.1 and exception handling in general for web applications.

    Chuck
  4. Hi, thanks a lot for your answers. The struts solution seems quite attractive but what I actually wanted to know is if Servlet specifications allow this behaviour....reading specs seems it's possible to catch declarative exceptions from Servlets too...but in practice it doesn't work...at least with Tomcat.......
    Francescp
  5. It's been a while that I've looked at the servlet spec, but I believe you can do something like this with the exception-type element. I think you it looks like this:

    <web-app>
     <error-page>
      <exception-type>javax.servlet.ServletException</exception-type>
      <location>/common/system_error.jsp</location>
     </error-page>
    </web-app>

    You basically can specify a JSP page (maybe another servlet, I can't remember) to go to when the exception occurs.

    Search the spec for "exception-type".

    Hope that helps,
    Chuck