Anand
Anand

Reputation: 21320

Handling exception when using HibernateDaoSupport

I am using Spring Hibernate integration in my application and DAO classes are extending HibernateDaoSupport.
Suppose I save some object using the code getHibernateTemplate().save(object); As Spring Hibernate integration doesn't mandate to write try-catch block, but suppose if any exception is thwron while saving that object. Then what is the best way to handle it? I means should I catch it in the service layer and wrap it in some user defined excpetions. Do I need to write try-catch in DAO layer method itself in case I want to log which method in DAO throws exception?

I have never used HibernateDaoSupport or Hibernate Template before so ignorant about exception handling. Please provide me your valuable inputs

Upvotes: 1

Views: 1662

Answers (2)

Boris Treukhov
Boris Treukhov

Reputation: 17774

Spring exception hierarchy is well documented.

Usually you can't do much if you have a data access exception, because in the working system this may be caused by the shortage of diskspace on the DB server, or network connection problems etc. Such exceptions are usually need to be logged and investigated as soon as possible.

There some recoverable errors, they can be handled with spring exception hierarchy, but imho most of them should be avoided during the developing phase, so your web server should validate as many things as possible, before it goes to the db.

If you want to set the exception logging see the similar questions:

Upvotes: 0

beny23
beny23

Reputation: 35018

The idea behind Spring using RuntimeException is that generally there are different types of exception:

  • Exceptions that you want to recover from (such as a DuplicateKeyException if a record that you're trying to insert already exists or the more general DataIntegrityViolationException if there was a DB constraint that was violated as a result of user input)
  • Exceptions that you can't recover from (the database is down)

For the first case, you may well handle the exception (either through a custom business exception, so that the view layer can redirect to the input page and provide a meaningful message)

For the second case, it would be easier to let the exception bubble up and have it handled by a generic exception handler that then displays a generic error page to the user. For this scenario it doesn't make sense to wrap the exception in a custom exception as you won't be able to recover. A blown up DB tends to be fatal.

So what I would do:

try {
   getHibernateTemplate().save(object);
} catch (DataIntegrityViolationException dive) {
   throw new BusinessValidationException(dive, "You've got the data wrong");
}

Upvotes: 2

Related Questions