Export (0) Print
Expand All

HTTP Error Trapping

 

Microsoft Corporation
October 2003

Applies to
    Microsoft® ASP.NET
    Microsoft Visual Basic® .NET
    Java Server Pages

Summary: Learn how error trapping works in Java and ASP.NET, and how to convert error trapping routines using the Java Language Conversion assistant. (9 printed pages)

Contents

Introduction
Errors in Java
JCLA Conversion of Error Handling
Error Trapping in ASP.NET
Conclusion

Introduction

Most applications—Web-based or otherwise—use some kind of error trapping to handle both expected and unexpected errors. Error handling in Web applications occurs on four different levels, each of which generally traps different types of errors.

  • Code-block level. Error handling done within a page in try-catch-finally blocks. Both JSP and Microsoft® ASP.NET support this structure.
  • Page level. Errors that occur on a JSP or ASP.NET page (for example, compilation errors) are generally processed by specialized error pages. Redirection to error pages is accomplished through page directives.
  • Application level. These errors apply to entire Web applications, and are generally handled and controlled by settings within configuration files, such as deployment descriptors in JSP applications or the web.config file in ASP.NET.
  • Server level. This applies to all applications running on a server, and is generally configurable in the settings for the particular server. Error handling of this nature is vendor-specific.

When an error occurs, it moves through these levels in a process called error bubbling. If an error can't be handled at the code block level, it bubbles up to the page level. If it can't be handled at the page level, it bubbles up to the application level, and finally to the server level. At each level, a different set of errors can be trapped and handled. If an error bubbles up through all four levels without being trapped, an explicit error message will probably be displayed to the user. This error message could contain insecure information, such as SQL scripts or hidden code. For this reason, you should try to make sure that any error that could possibly occur in your application is handled on one level or another.

Errors in Java

Error handling on all four levels is available in Java-based Web applications. In this section, we'll look at an example of error handling on each level.

Code-Level: Try-Catch-Finally Blocks

Try-catch-finally blocks are three-part structures in Java that work as follows:

  1. Code inside a try statement is executed until an exception is thrown, or it completes successfully.
  2. If an exception is thrown, the exception is handled by code inside a catch statement. There can be multiple catch statements in a try-catch-finally block, but each catch statement can only handle one exception.
  3. After all other try-catch processing is complete, the code inside the finally block executes. You don't have to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block.

Listing 1 shows a simple example of a try-catch-finally block in a Java application. Code like Listing 1 can also be used in JSP files, provided it is encompassed by <% %> brackets.

Listing 1. A try-catch-finally block

try {
   out = new PrintWriter(new FileWriter("out.txt"));
   out.println("Foo");
}
catch (IOException e) {
   System.err.println("I/O Exception occurred.");
}
finally {
   if (out != null) {
      System.out.println("Closing OUT");
      out.close();
   }
   else {
      System.out.println("OUT not open.");
   } 
}

Page Level: Page Redirect to Error Page

In Java Web applications, you can design your own error pages to which your JSP will automatically redirect the user if an exception occurs. This is accomplished by adding an errorPage attribute to a page directive at the top of a JSP. For example, the page directive in Listing 2 shows a page redirect to a custom error page.

Listing 2. Redirecting to an error page

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

If any exceptions occur in the Java code on this JSP page, the user will be automatically redirected to myError.jsp, which presumably will output some kind of user-friendly error message. To indicate that a particular JSP page is an error page, we simply add an isErrorPage attribute to that page's page directive, as shown in Listing 3.

Listing 3. Using isErrorPage

<%@ page isErrorPage="true" %>

Note that you must set isErrorPage to true if you want a JSP to be treated as an error page. Once you have set the isErrorPage attribute, you can use any of the following methods:

  • getMessage() returns a string with a descriptive error message (if there is one available).
  • printStackTrace() prints the execution stack to a specified buffer.
  • toString() returns a string with the specific class name of the exception and the message (for example, "IOException: File Not Found").

Listing 4 is a basic example of what your custom error page might look like:

Listing 4. Basic custom error page

<html>
   <%@ page isErrorPage="true" %>
   <body>
      An unexpected exception has occurred: <br/>
      <%=exception.toString()%> <br/>
      The stack trace is: <br/>
      <%exception.printStackTrace(new
      java.io.PrintWriter(out));%>
   </body>
</html>

See the Directives article for more information on directives in general.

Application Level: Deployment Descriptor Settings

General configuration for Java Web applications is usually done inside a deployment descriptor. Often, this deployment descriptor is an XML document named web.xml, which is located inside the WEB-INF directory of a WAR file or expanded Web application.

At the application level, you can specify that certain exceptions will be redirected to specific error pages. Suppose, for example, your application was a Web-based store, and you had a custom exception that occurred specifically when a user's order failed to process for some reason. You could add the code in to the web.xml file for your application in order to have the user forwarded to a special error page whenever an order exception occurred, as shown in Listing 5.

Listing 5. Using web.xml for application-level error handling

<error-page>
   <exception-type>exception.OrderException</exception-type>
   <location>/errorpage.html</location>
</error-page>

Alternatively, you can specify an HTTP error code in the <exception-type> element, instead of a Java exception class. Listing 6 shows an example of this.

Listing 6. Handling HTTP error codes in web.xml

<error-page>
   <exception-type>404</exception-type>
   <location>/404error.html</location>
</error-page>

The following table shows some of the more common HTTP errors for which you may want to design special error pages.

Table 1. Common HTTP errors

Error #Error CodeIIS Error Information
403ForbiddenHTTP Error 403 - Forbidden

HTTP 403.1 Forbidden: Execute Access Forbidden

HTTP 403.2 - Forbidden: Read Access Forbidden

404Page Not FoundHTTP 404 - File not found

HTTP 404.1 - Web site not found

500Internal Server ErrorHTTP 500 - Internal server error

HTTP Error 500-11 Server shutting down

501Not ImplementedError 501 - Not implemented

Server Level: Vendor-Specific Configuration

As previously mentioned, server-level error handling is vendor-specific. Each server package will have its own way of handling errors on a server-wide basis. Configuration at this level will affect all applications running on a particular server.

Although we won't get into the details of configuring error handling on any specific Java-based server, we will look at some server-level configuration options for Microsoft IIS later in this article.

Error Handling on the CodeNotes Website

The CodeNotes Web site does both code-level and page-level error handling. You can see an example of page-level error handling on almost any page in the site. For example, Listing 7 shows a fragment from the beginning of content_registeredHome.jsp, the content part of the CodeNotes home page.

Listing 7. An error page reference from content_registeredHome.jsp

<%@ page
   import="java.util.Iterator,
   com.codenotes.web.Links,
   com.codenotes.content.author.Author,
   com.codenotes.content.article.Article,
   com.codenotes.web.Attributes"
   errorPage="/jsp/error/content/content_welcomeError.jsp"
%>
<!-- begin content -->

CodeNotes has a special set of error pages it displays to the user in the event of an error. This prevents the user from seeing more detailed and less comprehensive error messages, and also provides them with information on how to contact server administrators if they see a problem occur.

The CodeNotes Web site currently has no error checking at the application or server level.

JCLA Conversion of Error Handling

The Java Language Conversion Assistant (JLCA) converts code-level and page-level error handling code perfectly. In fact, the JSP and ASP.NET code are virtually identical, and no conversion actually occurs.

Application-level and server-level error handling, unfortunately, do not convert.

Application-level handling is done in web.xml in JSP Web applications. ASP.NET applications use another XML document named web.config, which has a completely different structure; the JCLA is unable to convert information between these two documents. Therefore, you must manually include any application-level error handling elements in web.config in your new ASP.NET application. This process, including examples, is described in the Error Trapping in ASP.NET section of this article.

Server-level error trapping settings cannot be converted with the JLCA, as the server you will use to host your ASP.NET applications (IIS) is entirely different than whatever you used to host your JSP applications. So, again, you must reconfigure IIS manually in order to have it mimic the behaviour of your Java Web application server. The next section, "Error Trapping in ASP.NET," also contains details on how to configure error handling in IIS.

Error Trapping in ASP.NET

ASP.NET handles program exceptions in the same way as JSP does. Program exceptions are a general term for both code-level and page-level exceptions. This means that you can use the code from the JSP section of this article (such as try-catch-finally blocks and errorPage attributes within the page directive) and it will compile perfectly. If you are writing your Web applications in Microsoft Visual Basic® .NET, the try-catch-finally structure will be slightly different, as shown in Listing 8.

Listing 8. Using try-catch-finally in Visual Basic .NET

Try
   ' Entering try statement
Catch 
   ' Entering catch statement
Finally 
   ' Entering finally statement
End Try

However, application-level and server-level error trapping is quite different in ASP.NET. We will have a closer look at these two subjects in the following sections.

Application-Level Error Handling in ASP.NET

In ASP.NET, you use the <customErrors> handler to handle your application level exceptions. To use the <customErrors> handler, you must access your Web applications web.config file, located in C:\Inetput\wwwroot\<projectNameDir>. This file will also be accessible in the Solution Explorer in Microsoft Visual Studio® .NET.

Inside this configuration file, you can add the following lines of code to direct a user to your custom error page:

Listing 9. Using the <customErrors> tag

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.web>
   <customErrors mode=On
      defaultRedirect=yourCustomErrorPage.aspx />
   </system.web>
</configuration>

Inside the <customErrors> handler, the mode attribute has three settings: On, Off, and RemoteOnly. Each of these attributes offers advanced functionality. The On mode specifies that users will be directed to your custom error page, pointed at using the defaultredirect attribute. The Off mode specifies that users will be brought to the default ASP.NET error page (containing the details of any exception that occurs). The RemoteOnly mode is a hybrid of both the On and Off modes. Using this mode, all users not sitting at the Web server will see your custom error page (providing functionality as if the mode was set to On), while any user sitting at the actual Web server will see the default ASP.NET error page, containing the details of any exception (providing functionality as if the mode was set to Off). If no page is specified by the defaultredirect attribute, then ASP.NET will generate a basic (and not so user-friendly) error message. Once you make the appropriate changes in the web.config file, all that remains is for you to create a custom error page.

The <customErrors> element can have zero or more <error> child elements. Each one of these has two attributes:

  • statusCode specifies an HTTP error code.
  • redirect specifies a page to which the browser will redirect if the error code occurs.

In this way, you can have the application move to a special error page when certain HTTP error codes occur. If you don't have a specific <error> element for an error that occurs, the application will use the page specified in the defaultRedirect attribute. Listing 10 extends Listing 9 to add special handling for several HTTP error codes.

Listing 10. Using <error> elements

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.web>
      <customErrors mode=On
         defaultRedirect="yourCustomErrorPage.aspx" >
         <error statusCode="404" redirect="notFoundError.html">
         <error statusCode="403" redirect="forbiddenError.html">
      </customErrors>
   </system.web>
</configuration>

One thing you might notice is that ASP.NET, unlike JSP, does not allow you to redirect to custom pages if an error of a specific class occurs. Only HTTP error codes may be used for designing custom errors.

Server-Level Error Handling in ASP.NET

Microsoft IIS allows custom error handling at the server level in four different ways. The following list outlines the different error handling options:

  • If an error occurs, the server can display an automatically provided IIS error message.
  • The server can also output a customized error message if you have designed one for a specific error.
  • Instead of displaying an IIS error message, the server can redirect a user to a local URL (similar to what was done at the application level in the previous section).
  • Alternatively, the server can redirect a user to an external URL.

The functionality for all of these is controlled through the Internet Information Services window.

To work with Microsoft IIS custom errors, right-click the Default Web Site option, and then click Properties. The Default Web Site Properties window will appear. Click the Custom Errors tab to see a list of your default HTTP error pages.

To alter any of the error pages, select the HTTP error page from the list, and then click the Edit Properties button. The Error Mapping Properties window will appear. Here, you can specify that the HTTP error should be handled using one of the following options:

  • Default directs the user to the automatically provided IIS error page.
  • File directs the user to a custom file that you create. This file can either be a static page (for example, error403.html), or a generated page (for example, error403.pl).
  • URL directs the user to either a local URL or an external URL.

Note that all error pages automatically provided with Microsoft IIS version 5.1 are located in C:\WINDOWS\Help\iisHelp\common.

Conclusion

In both JSP and ASP.NET, there are four possible levels at which errors may be trapped: code-level (try-catch-finally blocks); page-level (within the page directive); application-level (within web.xml in Java or web.config in ASP.NET); and server-level (vendor-specific for whatever server you are using to host your applications).

Most applications, including the CodeNotes Web site, use primarily code-level and page-level error handling. This is generally enough for smaller scale projects; on larger projects you may want to implement more levels of hierarchy in your error handling, to prevent security issues and to ensure that all possible errors are trapped on the level in which they occur. Application-level error handling is primarily reserved for top-level issues on larger Web applications, and server-level error handling should be a last resort backup plan for any errors that were not caught at lower levels.

Using the JLCA, both code-level and page-level error handling convert perfectly. In fact, the code in ASP.NET is virtually identical to the code in JSP, and the conversion tool basically leaves them as is. Application-level and server-level handling, however, must be manually converted or added in ASP.NET applications, as the systems are quite different and the JLCA is not able to adequately map them for conversion.

Show:
© 2014 Microsoft