Pr.Pg Next Pg

Exception handling using Web.xml Configuration file tutorials

  • Consider, you have an ErrorHandler servelt which would be called whenever there is any defined exception or error. Following would be the entry created in web.xml.

 

<web-app>
    <error-page>
         <error-code>400</error-code>
         <location>/error400.html</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/error404.html</location>
    </error-page>
    <error-page>
        <exception-type>javax.servlet.ServletException</exception-type>
        <location>/servlet/ErrorDisplay</location>
    </error-page>
</web-app>

 

  • If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception:

<error-page>

<exception-type>java.lang.Throwable</exception-type >

<location>/ErrorHandler</location>

</error-page>

 

  • Following are the points to be noted about above web.xml for Exception Handling:

    1. The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml.

    2. If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then ErrorHandler servlet would be called.

    3. If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet.

    4. You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept.

  • An error-handling servlet has access to several request attributes that it can use to describe the error. The error page also has access to the request and response objects associated with the page that generated the error.

  • For example, the java.lang.Throwable object associated with any exceptions can be accessed with the following code:

Throwable throwable = (Throwable)

request.getAttribute("javax.servlet.error.exception");

  • You can access the server response code with this code:

String status_code =((Integer)request.getAttribute
("javax.servlet.error.status_code")).toString();

Pr.Pg border                                              Next Pg