我面临一个非常特殊的情况。我在Spring 3.0.5中使用休眠模板进行数据库操作。当我第一次尝试插入User模型时,抛出了DataAccessException,我抓住了它。现在,我希望重试同一数据库操作3次。第二次,没有异常被抛出。

这是代码:

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);
}
}
catch (Exception e) {
/* not coming inside this block too second time onwards */
System.out.println("Pure Exception");
}
}

return id;
}

}


我读到RuntimeExceptions不应该被捕获。然后如何重试该操作。我应该在服务层重试吗?我想念什么吗?任何帮助表示赞赏。

最佳答案

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


  未检查的异常是异常
  不需要在
  throws子句。他们延伸
  RuntimeException。一个未经检查的
  异常表示意外
  问题可能是由于错误
  在代码中。


由于DataAccessExceptionRuntimeException,因此您可能想检查引起异常的真正原因并进行修复,而不是捕获该异常并重试该操作。

07-28 00:58
查看更多