Servlet Exception Handling
When a Servlet throws an exception, the Web container searches the web.xml file for a configuration that matches the thrown exception type using the exception-type element.
You must use the error-page element in web.xml to specify the Servlet call that responds to a specific exception or HTTP status code.
web.xml Configuration
Suppose there is a Servlet named ErrorHandler that is called whenever a defined exception or error occurs. The following entries would be created in web.xml:
<!-- servlet definition -->
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<!-- error-code related error pages -->
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/ErrorHandler</location>
</error-page>
<!-- exception-type related error pages -->
<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>
If you want a common error handler for all exceptions, you should define the following error-page instead of separate error-page elements for each exception:
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
Here are some points to note about the above web.xml exception handling:
The Servlet ErrorHandler is defined like any other Servlet and is configured in web.xml.
If an error status code occurs, whether it is 404 (Not Found) or 403 (Forbidden), the ErrorHandler Servlet will be called.
If the Web application throws a ServletException or IOException, the Web container will call the ErrorHandler Servlet.
You can define different error handlers to handle different types of errors or exceptions. The above example is very generic, and we hope you can understand the basic concepts through this example.
Request Attributes - Error/Exception
The following is a list of request attributes that the error handling Servlet can access to analyze the nature of the error/exception:
Number | Attribute & Description |
---|---|
1 | javax.servlet.error.status_code <br>This attribute provides the status code, which can be stored and analyzed after being stored as a java.lang.Integer data type. |
2 | javax.servlet.error.exception_type <br>This attribute provides information about the exception type, which can be stored and analyzed after being stored as a java.lang.Class data type. |
3 | javax.servlet.error.message <br>This attribute provides the exact error message, which can be stored and analyzed after being stored as a java.lang.String data type. |
4 | javax.servlet.error.request_uri <br>This attribute provides information about the URL invoking the Servlet, which can be stored and analyzed after being stored as a java.lang.String data type. |
5 | javax.servlet.error.exception <br>This attribute provides information about the exception generated, which can be stored and analyzed after being stored as a java.lang.Throwable data type. |
6 | javax.servlet.error.servlet_name <br>This attribute provides the name of the Servlet, which can be stored and analyzed after being stored as a java.lang.String data type. |
Servlet Error Handler Example
Below is a Servlet example that will handle error handlers for any errors or exceptions you define.
This example gives you a basic understanding of exception handling in Servlets. You can use the same concepts to write more complex exception handling applications:
// Import necessary Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class ErrorHandler extends HttpServlet {
// Method to handle GET method request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Throwable throwable = (Throwable)
request.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer)
request.getAttribute("javax.servlet.error.status_code");
String servletName = (String)
request.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null){
servletName = "Unknown";
}
String requestUri = (String)
request.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null){
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "tutorialpro.org Error/Exception Information";
String docType = "<!DOCTYPE html>\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n");
out.println("<h1>tutorialpro.org Exception Information Example</h1>");
if (throwable == null && statusCode == null){
out.println("<h2>Error Information Missing</h2>");
out.println("Please return to <a href=\"" +
response.encodeURL("http://localhost:8080/") +
"\">homepage</a>.");
```java
} else if (statusCode != null) {
out.println("Error Code : " + statusCode);
} else {
out.println("<h2>Error Information</h2>");
out.println("Servlet Name : " + servletName +
"</br></br>");
out.println("Exception Type : " +
throwable.getClass().getName() +
"</br></br>");
out.println("Request URI: " + requestUri +
"<br><br>");
out.println("Exception Message: " +
throwable.getMessage());
}
out.println("</body>");
out.println("</html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Compile ErrorHandler.java in the usual way and place your class files in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes
.
Let's add the following configuration in the web.xml
file to handle exceptions:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>com.tutorialpro.test.ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/TomcatTest/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/TomcatTest/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/ErrorHandler</location>
</error-page>
</web-app>
Now, try using a Servlet that generates an exception, or enter a wrong URL, which will trigger the Web container to call the ErrorHandler Servlet and display appropriate messages. For example, if you enter a wrong URL (like: http://localhost:8080/TomcatTest/UnKonwPage), it will display the following result: ```