ServletException root cause

Java’s Throwable class defines the getCause() method for accessing the cause of the exception.  This method returns a Throwable object which itself could have a cause.  By traversing down this chain you can find the root cause of an exception.

However for some unknown reason in ServletException the getRootCause() method was added.  Therefore when trying to determine the root cause of an exception in a J2EE environment one has to check what type of exception you have.  I do this in the following code.

  /**
   * Logs all the nested exceptions for the specified exception.
   *
   * @param ex the exception
   */
  protected void logNestedExceptions(Throwable ex) {
    int count = 1;
    Throwable cause = getCause(ex);
    while (cause != null) {
      logger.error("Nested Exception " + count, cause);
      cause = getCause(cause);
      count++;
    }
  }

  /**
   * Gets the cause of the exception.
   *
   * @param ex the exception
   * @return the cause
   */
  protected Throwable getCause(Throwable ex) {
    Throwable cause;
    if (ex instanceof ServletException) {
      ServletException sex = (ServletException) ex;
      cause = sex.getRootCause();
    }
    else {
      cause = ex.getCause();
    }
    return cause;
  }

Finally you need to configure web.xml to use your SiteMap servlet.

<servlet>
    <servlet-name>sitemap</servlet-name>
    <servlet-class>com.betweengo.servlet.SiteMap</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>sitemap</servlet-name>
    <url-pattern>/sitemap.xml</url-pattern>
</servlet-mapping>

Leave a Reply

Your email address will not be published. Required fields are marked *