You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Brian McGovern <bm...@imediainc.com> on 2005/02/15 23:06:32 UTC

RE: Proper n tiered exception handling -- RESOLVED -- I think.

Many thanks to everyone who responded, all very helpfull.  

The approach I've taken looks like this.  I still think I've got an issue with nested exceptions.  But this is a good start.

Data Conn Class Snippet
-----------------------------------
try{
	//make the conn here
}catch(NamingException zNamingEx){
        	Logger.logMessage("EXCEPTION::DBConnection::getConnection::Naming Exception--" +zNamingEx);
            throw new Exception( zNamingEx.toString(),  zNamingEx);
-----------------------------------

Data Class that catches the conn error.
-----------------------------------
 try {
                zConnection_m = zDBConnection_m.getConnection();
            }catch(Exception zAppEx){
                Logger.logMessage("EXCEPTION::MyClass.getRepByID::Couldn't Get DB Connection--" +zAppEx);
                throw zAppEx;
            }
-----------------------------------

Application Exception
-----------------------------------
public class ApplicationException extends ExceptionHandler {
   public ActionForward execute(
      Exception ex,
      ExceptionConfig ae,
      ActionMapping mapping,
      ActionForm formInstance,
      HttpServletRequest request,
      HttpServletResponse response)   throws ServletException {
	  
	request.setAttribute("ApplicationException", ex);
	      
      return new ActionForward(ae.getPath());
   }
}


-----------------------------------
struts-config
-----------------------------------
<global-exceptions> 
   <exception key="error.application_error" 
   		handler="com.imediainc.nycballet.nycbbuilder.util.exception.ApplicationException"
   		type="java.lang.Exception"
        path="/error.jsp"/>
</global-exceptions>

-----------------------------------
error.jsp
-----------------------------------

<bean:write name="ApplicationException" property="message" />


Thanks


-----Original Message-----
From: Brian McGovern [mailto:bmcgovern@imediainc.com]
Sent: Tuesday, February 15, 2005 3:12 PM
To: Struts Users Mailing List; jgkennedy@mindspring.com
Subject: RE: Proper n tiered exception handling


This worked for me for the most part.  I now have a global exception and am able to get the last trace within your comment tags.  But in my data class I'm closing my db connections and result sets in try catch blocks, so in this case, the user would see the global error page in the following case if a connection could not be closed for some reason which I know would be very rare, but still:

	 if (zDBConnection_m != null) {
                try {
                    zDBConnection_m.closeConnection();
                    Logger.logDebug("Closed DB Connection in MyData.getRepByID ");
                } catch (Exception zCONNEx) {Logger.logMessage("EXCEPTION::MyData.getRepByID::Couldn't close CONN--" +zCONNEx);}
       }

This is not a fatal error and I don't want the user to see this.  So my follow up question is can I model a single exception to be thrown in my critical catch blocks throughout all tiers of my app that can extend off a struts framework class that shows the error to the user though a jsp page defined in struts-config.xml

Im pretty sure im reading that you can, but am having trouble understanding the theory.  I'd LOVE an example of an ApplicationSpecificException class.

Thanks


-----Original Message-----
From: jgkennedy@mindspring.com [mailto:jgkennedy@mindspring.com]
Sent: Tuesday, February 15, 2005 12:00 PM
To: Struts Users Mailing List
Subject: RE: Proper n tiered exception handling


I'm sure your right Dan.  That code is pretty old now and I would do it differently today.  But at the time given my understanding, this is what I came up with.  Actually couldn't tell you why I did it that way :)

The thing to focus on here in the example is the use of HTML comments to "embed" the actually problem.

Good stuff though, thanks


-----Original Message-----
From: Daniel Lipofsky <da...@bricsnet.com>
Sent: Feb 15, 2005 11:52 AM
To: Struts Users Mailing List <us...@struts.apache.org>
Subject: RE: Proper n tiered exception handling

Why do you do all that work to print the stack trace?
Shouldn't exception.printStackTrace(out) do what you want?
This also follows the exception.getCause() chain and
prints out nested exceptions.

As a side note, if you really want to log
all nested exceptions then you have to do a little extra
work because some exceptions implement nesting in a way
that is not returned by getCause() (mostly because it
is an old implementation).  I do the following:

log.error(exception.getMessage(), exception);
// struts utils often save original exception under
Globals.EXCEPTION_KEY
Throwable t = (Throwable) pageContext.
    getAttribute(Globals.EXCEPTION_KEY,
                 PageContext.REQUEST_SCOPE);
if (t != null && t != exception && t != exception.getCause()) {
    log.error("original exception: ", t);
}
if (exception instanceof JspException) {
    Throwable t2 = ((JspException)exception).getRootCause();
    if (t2 != null && t2 != t && t2 != exception && t2 !=
exception.getCause())
        log.error("root cause: ", t2);
} else if (exception instanceof EJBException) {
    Throwable t3 = ((EJBException)exception).getCausedByException();
    if (t3 != null && t3 != t && t3 != exception && t3 !=
exception.getCause())
        log.error("caused by: ", t3);
}

- Dan

> -----Original Message-----
> From: jgkennedy@mindspring.com [mailto:jgkennedy@mindspring.com] 
> Sent: Tuesday, February 15, 2005 8:35 AM
> To: Struts Users Mailing List
> Subject: RE: Proper n tiered exception handling
> 
> I probably have not shown you enough in terms of setup.  
> There is more to configure this completely.  I will try to 
> outline this shortly.  To answer your question , I don't 
> rethrow anything.  It's not necessary.  Your struts actions 
> have the following signature:
> 
> 	public ActionForward execute(ActionMapping mapping, 
> ActionForm form,
> 		HttpServletRequest req, HttpServletResponse resp)
> 		throws Exception
> 	{
>                            .......
>                  }
> 
> Any exception thrown within this method with propagate up 
> through the exception handling framework.  Whether it's a 
> SQLException, RemoteException or any checked or runtime 
> exception will flow upward.  You delcare where to forward to 
> (what page).  I designed a generic error handling jsp, 
> because I did not want to design a separate JSP for every 
> type of exception.  This is a preference thing.  My way was 
> right for me.  Here is my JSP for handling errors:
> 
> <%@page import="java.util.*" %>
> <%@taglib uri="/WEB-INF/taglibs-log.tld" prefix="log" %>
> <%@taglib uri="/WEB-INF/fmt.tld" prefix="fmt" %>
> <%@taglib uri="/WEB-INF/c.tld" prefix="c" %>
> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
> 
> <%
> 		Throwable t = 
> (Throwable)request.getAttribute("org.apache.struts.action.EXCEPTION");
> 		if ( t!= null)
> 		{
> 			StackTraceElement [] trace = t.getStackTrace();
> 			int size = trace.length;
> 			out.print("<!--\n\n");
> 			out.print(t.toString());out.print("\n");
> 			for (int i=0; i < size; i++)
> 			{
> 				out.print(trace[i].toString());
> 				out.print("\n");
> 			}
> 			out.print("\n\n-->");
> 		}
> 
> %>
> <!-- #BeginEditable "body" -->
> 
> 
> 	<!-- center box header image --> 
> 	<div id="centerBoxTopErrorTall2">System Error</div> 
> 	
> 	<!-- begin center box content stretch image -->
> 	<div id="centerBoxStretch2">
> 
> 	<table width="95%" border="0" cellpadding="0" cellspacing="0">
> 		<tr >
> 			<td>
> 				<div id="infoBoxError">
> 					<!-- left nested inside 
> infobox -->
> 
> 					<html:errors 
> bundle="systemerrorbundle"/>
> 
> 				</div>
> 			</td>
> 		</tr>
> 	</table>		
> 		
> 	</div>
> 	<!-- end center box content stretch image -->
> 	
> 	<!-- center box content footer image -->
> 	<div id="centerBoxBtm2"> </div>
> 
> 
> <!-- #EndEditable "body" -->
> 
> 
> There's more to this story.  Notice the line:
> <html:errors bundle="systemerrorbundle"/>
> 
> This is where I supply a customer message.  The message is 
> externalized in a properties file for I18N.  This is my 
> syserror.jsp page which is referenced in the struts.xml config.
> 
> 
> 
> -----Original Message-----
> From: Brian McGovern <bm...@imediainc.com>
> Sent: Feb 15, 2005 11:24 AM
> To: Struts Users Mailing List <us...@struts.apache.org>, 
> jgkennedy@mindspring.com
> Subject: RE: Proper n tiered exception handling
> 
> Jim,
> So in this approach you really dont use any try catch blocks 
> at all? or you just re - throw the original exception that you caught?
> 
> How do you grab the error on the JSP page? 
> 
> Thanks
> 
> -----Original Message-----
> From: jgkennedy@mindspring.com [mailto:jgkennedy@mindspring.com]
> Sent: Tuesday, February 15, 2005 11:16 AM
> To: Struts Users Mailing List
> Subject: Re: Proper n tiered exception handling
> 
> 
> I use declaritive exception handling which is built into 
> Struts.  Works great for me.  I really don't use custom 
> exceptions that much any more because it's harder to track 
> the original error.  Also, I don't clutter my code with alot 
> of try/catch blocks unless it's absolutely necessary.  I 
> allow all exceptions to propagate through the Struts built-in 
> exception handling framework.
> 
> Here is an example of declaritive exception handling in the 
> struts config:
> 
> 	<global-exceptions>
> 		<exception
> 			key="error.application.nullpointer"
> 			type="java.lang.NullPointerException"
> 			
> path="/tmpl_main2.jsp?error=/error/null.jsp&pagetitle=error.ti
> tle.key">
> 		</exception>
> 		<exception
> 			key="error.application.parse"
> 			type="java.text.ParseException"
> 			
> path="/tmpl_main2.jsp?pageleft=/mainmenu.jsp&pagecenter=/error
/syserror.jsp&pagetitle=error.title.key">
> 		</exception>
> 		<exception
> 			key="error.application.import.zip"
> 			type="java.util.zip.ZipException"
> 			
> path="/tmpl_main2.jsp?pageleft=/mainmenu.jsp&pagecenter=/error
/syserror.jsp&pagetitle=error.title.key">
> 		</exception>
> 		<exception 
> 			key="error.application.unhandled" 
> 			type="java.lang.Exception" 
> 			
> path="/tmpl_main2.jsp?pageleft=/mainmenu.jsp&pagecenter=/error
/syserror.jsp&pagetitle=error.title.key">
> 		</exception>
> 
> When these exception types are thrown, the user is forwarded 
> to the proper custom page.  If your creative you can grab the 
> current error and print the stack trace as an HTML comment 
> within the page for your review.  You can then view the 
> exception stack trace by selecting view/source from you 
> browser.  Only show the user and nice "pretty" message.
> 
> 
> Jim
> 
> 
> -----Original Message-----
> From: Brian McGovern <bm...@imediainc.com>
> Sent: Feb 15, 2005 10:28 AM
> To: user@struts.apache.org
> Subject: Proper n tiered exception handling
> 
> I'm looking to get a handle on best exception handling 
> practices in my app.  Kinda beginner question i guess, sorry.
> 
> Im catching the various sql and naming exceptions in the data 
> classes and logging and throwing a custom exception called 
> ApplicationException which is blank and provided below.  I've 
> read up but an still a little confused on how exactly to 
> build this exception class to extend the available struts 
> exception classes that would gracefully map to an error 
> display jsp where i could display the error to the user.  
> Right now I just get the HTTP status 500 strack trace on the screen.  
> 
> Controller snippet that catches the data obj's thrown 
> ApplicationException:
> --------------------------------------------------------------
> ----------
> try {
> 	zRepBeanBn = 
> MyData.getRepByID(StringUtils.convertToInt(request.getParamete
> r("RepID")));
> }catch (ApplicationException zAppEx){
> 	throw zAppEx;
> }
> --------------------------------------------------------------
> ----------
> 
> ApplicationException that needs work:  How do I extend this?
> --------------------------------------------------------------
> ----------
> public class ApplicationException extends Exception {
>     public ApplicationException(String message) {  }
> }
> --------------------------------------------------------------
> ----------
> 
> Thanks
> 
> 
> 
> 
> 
> 
> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
> 
> 

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org