where to handle spring DataAccessException

rohit picture rohit · May 20, 2012 · Viewed 11.3k times · Source

I develop an application using Struts, Spring, and Hibernate.

My DAOs uses spring jdbc and all its method throws DataAccessException(that is uncheked).

Where should I handle this exceptions? I know it's an unchecked exception but I think I need to tell the user if there's a problem with the db or it's connection.

I think I should rethrow the DataAccessException from my service class methods to be catched by Controller. Is this a good practice?

I've looked at the samples from Spring package and didn't find any Exception handling in the domain or service area. The DataAccessException seems to be ignored after leaving dao area.

Please suggest a good design for this matter.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · May 20, 2012

The DataAccessException seems to be ignored after leaving dao area.

And that's a good thing! Let it fly down through the whole stack. You probably have transactions on service layer - the exception will transparently cause the outermost transaction to be rolled-back. Great!

Now it will find its way to the controller. If you catch it in the Struts controller, you can e.g. return different view. But most likely you don't want to handle exception in each and every Struts action. So let the exception fly even further down. At some point Struts will catch that exception and try to handle it. Struts has some sophisticated error handling mechanisms, you'll find plenty of information about them. Typically it will invoke some custom action or error screen depending on exception type.

Finally, if even Struts can't handle the exception, it will be rethrown to the container, causing HTTP 503 with exception details being returned.

As you can see you can control exceptions on a lot of levels, typically lower is better.