开发者

Retry after Spring throws DataAccessException not working

I am facing a very peculiar situation. I am using hibernate template with spring 3.0.5 for DB operations. When I try to insert a User model the first time, a DataAccessException is thrown, which I catch. Now I wish to retry the same DB operation for say 3 times. The second time when it, no exception is thrown.

Here is the code:

package com.user.profile.dao;

@Repository("userProfileDAOImpl")
public class UserProfileDAOImpl implements IUserProfileDAO {

@Autowired
private HibernateTemplate hibernateTemplate;

public Long insertUserProfileData(User user) throws AppNonFatalException {
Long id = null;
int retryCount = 0;

while (retryCount < 3) {
try {
id = (Long)hibernateTemplate.save(user);
}
catch (DataAccessException e) {
e.printStackTrace();
retryCount++;
System.out.println("Retry Count = " + retryCount); 
if (retryCount > 3) {
throw new AppNonFatalException(e.getLocalizedMessage(), "10000", e.getMessage(), e);
} 
}
c开发者_运维技巧atch (Exception e) {
/* not coming inside this block too second time onwards */
System.out.println("Pure Exception");
}
}

return id;
}

}

I read that RuntimeExceptions should not be caught. Then how do I retry the operation. Should I retry at the service layer? Am I missing something? Any help is appreciated.


From https://community.oracle.com/docs/DOC-983543:

Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code.

Since DataAccessException is a RuntimeException, you might want to check what is the real cause of the exception and fix it instead of catching it and retry the operation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜