Servlet Exception

When ever exception is thrown in servlet its handler is searched by container before providing details with default handler.

We can specify common exception handler in web.xml as:

<servlet>
    <servlet-name>ErrorHandler</servlet-name>
    <servlet-class>ErrorHandler</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ErrorHandler</servlet-name>
    <url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/ErrorHandler</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/ErrorHandler</location>
</error-page>

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

<error-page>
    <exception-type>java.io.IOException</exception-type >
    <location>/ErrorHandler</location>
</error-page>

Now when ServletException will occur or error code:403,404 then ErrorHandler servlet will get called.

In ErrorHandler Servlet we can get the exceptionrror details as follows:

To get Throwable exception object:-

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

To get status code:-

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

To get servlet name from which exception is thrown:-

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