how to handle hibernate exceptions
I hav开发者_运维知识库e few questions like
Which is the right place to handle a Hibernate
RuntimeException
. DAO Layer? ServiceLayer?For instance, I have
saveCustomer
and the transaction fails, how can I inform the user throughExceptions
?I'm using the
OpenSessionInView
pattern, which will commit the transaction only after the view is rendered. In this case, if the transaction fails, How can I inform the user about this?
Generally it's a good idea to handle exceptions at the point in your code where you have the most information on how to handle them (or generate an appropriate error message with enough information). In the j2ee apps I've developed I usually have a transactional service layer that stitches together various DAO calls and I usually handle hibernate-specific runtime exceptions and all other data-related exceptions in the service layer. That said, if there's a pile of logic within a DAO where something bad could go wrong, it's probably not a bad idea idea to catch it there, add some error message context, and then rethrow it up the chain.
If an exception happens within your transaction you can either leave it uncaught or rethrow it with some additional context. This way your transaction manager knows to rollback the transaction. Always have an exception handler set up in your view/controller layer to handle any application-specific runtime exceptions that were thrown from your service layer calls. Inspect them for additional error messages and then use them to inform the user appropriately.
As far as I know, the default behavior when an exception is thrown out of a transaction it should rollback and not get committed at all. The answer to #2 really answers this one as well, i.e., if you've wrapped all your view layer's service calls in try/catch blocks or configure one globally via your web framework you shouldn't have a problem notifying the user that something bad-wrong happened.
This article (Best Practices for Exception Handling) has a decent overview on exception handling in general that you may also find useful.
Catch the exception where you can do something with the exception. If you catch it in DAO layer, then the information specific to dao layer needs to be extracted. e.g. if it is can not insert null value, then log the field details where it is failing. Once done, then the service layer can do business related processing of the exception directly or in wrapped format. You can see these common mistakes in exception handling. This is not applicable to specific hibernate example but in general to all.
精彩评论