2010/11/28

Configuring a JSP error page

Hi guys.

It's awful to visit a web site and receive an error page that does not explain what the hell had happened. However it's very easy to configure a nice error page to be shown when an unexpected error happens.

1) Create a new JSP page, with the follow code:

<%@ page isErrorPage="true" import="java.io.*" %>
<html>
    <head>
        <title>Error Page</title>
    </head>

    <body>
        <h2>Unexpected error</h2>
        <p><b><%= exception.toString() %></b></p>
        <p><%=
            StringWriter sw = new StringWriter(); 
            PrintWriter pw = new PrintWriter(sw); 
            exception.printStackTrace(pw); 
            out.print(sw); 
            sw.close(); 
            pw.close();
        </p>
    </body>
</html>

Explaining the code:
  • The attribute errorPage=true identifies the JSP page as an error page
  • As an errorPage, an object called "exception" is made available. Its type is java.lang.Throwable
  • We used the method exception.toString() to return a description of the exception
  • We also used the method exception.printStackTrace to give more information about what happened
There are a lot of other usefull information that you may use in this error page. Just take a look at the java.lang.Throwable class.

2) Configure the application

Now that we have our error page, let's configure the application to call it when an unexpected exception happens. There are two ways to do that:

2a) Configure each JSP page to call the error page when an unexpected exception happens.

Include the attribute errorPage on the top of the page code:

<%@ page errorPage="errorPage.jsp" %>

2b) Configure the web.xml file to call the error page for the entire application

Use the tag error-page to configure a JSP page to be called according to the error code:

<error-page>
    <error-code>500</error-code>
    <location>errorPage.jsp</location>
</error-page>

Explaining the code:

  • The tag error-page tells the application server what to do when an error happens
  • The tag error-code specifies what error should be catch
  • The tag location specifies what page will be show when the error happens

Some common error codes are:

  • 404 - Page not found
  • 500 - Application error (exception)
  • You may find other code descriptions at this link

That's it! Now your application has a beautiful and useful error page.


No comments:

Post a Comment