Spring抛出DataAccessException后重试不起作用
我面临着一个非常特殊的情况。我使用 hibernate 模板和 spring 3.0.5 进行数据库操作。当我第一次尝试插入用户模型时,抛出了 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。那我该如何重试该操作。我应该在服务层重试吗?我错过了什么吗?任何帮助表示赞赏。
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);
}
}
catch (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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 https://community.oracle.com/docs/DOC-983543:
由于
DataAccessException
是RuntimeException
,因此您可能需要检查异常的真正原因并修复它,而不是捕获它并重试操作。From https://community.oracle.com/docs/DOC-983543:
Since
DataAccessException
is aRuntimeException
, you might want to check what is the real cause of the exception and fix it instead of catching it and retry the operation.