How do I create a JSP error page to handle exceptions?
Author: Deron Eriksson
Description: This Java tutorial describes how to create a JSP error page to handle exceptions.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20
When an exception is thrown in your web application and it is not caught, you will typically see the result featuring the exception displayed in your browser window, as shown here: Rather than displaying the above default page when an exception occurs, you can redirect the user to a custom-written error page for a particular type of exception. You can do this via the error-page element in web.xmlW, in which you can specify an exception-type and the location of the resource where a user should be sent if an error occurs. In this example, I specified the exception-type as java.lang.Throwable so that all exceptions would be sent to the error.jsp page. <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.jsp</location> </error-page> I created the error.jsp page shown below. error.jsp<%@ page isErrorPage="true" import="java.io.*" contentType="text/plain"%> Message: <%=exception.getMessage()%> StackTrace: <% StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); exception.printStackTrace(printWriter); out.println(stringWriter); printWriter.close(); stringWriter.close(); %> Notice that at the top of the error.jsp file that I specified isErrorPage="true". This enables us to use the 'exception' object on the jspW, as demonstrated in the scriplet code. For this example, I specified the contentType to be "text/plain" so that we could easily view the stackTrace. (Continued on page 2) |