[ Team LiB ] |
Error HandlingYou usually won't be able to find all the errors in your Web application no matter how much debugging you do. Eventually, an error is going to crop up somewhere. In a servlet, you can put a try-catch block around your code to make sure the servlet doesn't throw an exception but goes to an error-handling page instead. Specifying an Error Page for a JSPFor a JavaServer Page, you might be able to insert a try-catch block, but there's a better solution. You can specify an error page for each JSP. Whenever the page throws an exception, the JSP engine automatically invokes the error page. The error page can then log the exception (which is passed via the exception built-in variable) and display some sort of response to the user. To set up an error page, use the <%@ page errorPage="xxx" %> directive. For example, Listing 11.3 shows a JavaServer Page that intentionally throws an exception. Listing 11.3 Source Code for ThrowError.jsp
Listing 11.4 shows the error page that was specified in Listing 11.3. Notice that the error-handling page includes the directive <%@ page isErrorPage="true" %>. This directive causes the JSP compiler to generate the exception instance variable. Listing 11.4 Source Code for ShowError.jsp
Error Pages and Output
Specifying Error Handlers for Web Server ErrorsSome errors that occur in an application can't be detected from a JSP or servlet. For instance, if you have a typo in one of your HTML hyperlinks, the Web server generates an HTTP 404 error. Because no servlet or JSP is involved when the 404 error occurs, there is normally no way to know about the error until the user calls up on the phone asking about it. Fortunately, the servlet API specification provides a hook that enables you to specify an error handler for a specific Web server error or Java exception. The only difficulty you'll have in setting up these error handlers is that you must put them in a deployment descriptor, which is a file describing the contents of a Web application. Appendix B, "Packaging a Web Application," tells you everything you need to know about setting up a deployment descriptor and deploying a Web application on a server. To add a handler for the 404 error, you just add the following information to the deployment descriptor:
Instead of a numeric error code, you can also specify a Java exception type for the error page. For example, whenever a java.lang.NullPointerException occurs in a JSP or servlet, you can invoke a special handler by adding the following information to the deployment descriptor:
The location for an error page might be an HTML page, a JSP, a servlet, or some other kind of Web resource. |
[ Team LiB ] |
No comments:
Post a Comment