File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes How to catch exceptions in JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "How to catch exceptions in JSP" Watch "How to catch exceptions in JSP" New topic

How to catch exceptions in JSP

Brad Ward

Joined: Sep 24, 2003
Posts: 5
I am writing a custom tag library and I am looking for information on how to trap the JspTagExceptions and JspExceptions in a global manner (i.e. where can I put a single catch(JspException) statement to catch everything on any JSP page.
The Javadocs for the javax.servlet.jsp.JspException class has the following statement: "A generic exception known to the JSP engine; uncaught JspExceptions will result in an invocation of the errorpage machinery".
What I am looking for are some online resources or pointers on where to learn more about this vague reference to "the errorpage machinery".
Anybody got any pointers?
Matthew Phillips
Ranch Hand

Joined: Mar 09, 2001
Posts: 2676
I haven't tried this before, but it seems like it should work. You could use the error page tag in the web.xml to map all the exceptions you want to catch to either a url that will handle the exceptions, similar to the way you would handle http error codes.
I refreshed myself on the information in the web.xml dtd, but I don't recall where I read it to begin with.

Matthew Phillips
Brad Ward

Joined: Sep 24, 2003
Posts: 5
Thank you Matthew! Your suggestion did the trick, very easily.
Others sent some links on how to handle errors via the page level specification (i.e. the <%@ page errorPage="error.jsp" %> statement), but I was looking for something I could set once and all errors on all .jsp pages would get trapped and redirected to the same error page.
Here is what I did:
In the web.xml file, I added the
... stuff...
... stuff...
Note you can catch any exception you like; I'm using java.lang.Exception to catch all errors.
Next, I created the error.jsp file (which I found on one of the tutorial pages on the sun site, I think). The error.jsp file looks like this:
<%@ page isErrorPage="true" %>
Error Page
Received the exception:<br>
<font color=red>
<%= exception.toString() %>
That's it. Worked like a champ.
I agree. Here's the link:
subject: How to catch exceptions in JSP
It's not a secret anymore!