Hi guys, I am writing a web app with Struts and I would like to do a better job of handling errors. Okay so I have a Struts action class that calls a class and runs a method that accesses the database and returns the results into a list. Lets say the DB is messed up or the SQL fails, my Custom SQL class throws out a SQLExeception, with the details of what went wrong. OKay, so I go through a first method into the bottom one to run this method, if I want to throw that Exception all the way out to the Servlet, do I need of a Throws of the Exeception on each method? Finally, if I am getting these SQLExeceptions, do I need to keep throwing, or can I just throw a standard with the message text and catch it it the Action and an add an Error to the Errors colelction for the user, and then Log4j the exeception out for the developers?
Our approach has been to log exceptions in the method where they are thrown. This helps developers go directly to the source of the problem. Then we'll either rethrow the exception and have it handled higher up in the call stack or throw a custom exception that is caught in the Action to indicate that something bad has happened. Then we'll create a user-friendly ActionError to be displayed to the user instead of the cryptic (to the user, that is) message in the original exception.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
This calls for a chaining-exception technique. http://husted.com/struts/tips/015.html Basically, each layer in your application show have its own exception. So let say, your Action calls your Service class, which in turns calls your DAO class to get the results you need. You would have a DAOException, and a ServiceException. All your methods in your DAOs would declare DAOExceptions, and all your Service class methods would contain ServiceExceptions. When exceptions occur at your DAO layer (i.e. SQLException), you would wrap this specific error, like SQLException into your DAOException, with a description possibly, and re-throw it back up the layer (which would be the Service). The Service could then re-wrap the DAOException into a ServiceException, and re-throw it back for the clients to handle. Hope this helps
posted 16 years ago
It does help Hung, both answers were very well done! I like the exception chain idea. I do have a bit of a problem, we have some tags in our JSP pages that can call methods from the service objects, so there it can be hard to get those exceptions to behave, but I think I can work it out. I have been wanting an excuse to wrap those methods that can be called from a tag in a JSP, they seem to always be problem.