>我在使用 Hibernate 实现的事务服务层中有以下方法:
@Override
public void activateAccount(String username, String activationCode)
throws UsernameNotFoundException, AccountAlreadyActiveException,
IncorrectActivationCodeException {
UserAccountEntity userAccount = userAccountRepository.findByUsername(username);
if (userAccount == null) {
throw new UsernameNotFoundException(String.format("User %s was not found", username));
} else if (userAccount.isExpired()) {
userAccountRepository.delete(userAccount);
throw new UsernameNotFoundException(String.format("User %s was not found", username));
} else if (userAccount.isActive()) {
throw new AccountAlreadyActiveException(String.format(
"User %s is already active", username));
}
if (!userAccount.getActivationCode().equals(activationCode)) {
throw new IncorrectActivationCodeException();
}
userAccount.activate();
userAccountRepository.save(userAccount);
}
如您所见,else if (userAccount.isExpired())
块中,我想先删除userAccount
,然后抛出异常。但是,由于它引发异常并突然退出该方法,因此不会执行删除。
我想知道是否有任何方法可以在抛出异常时保留删除操作。
我也遇到了同样的情况。
我的解决方案是使用Spring Security FailureHandler
使用此类,您可以在失败事件之后执行操作。
看这里, https://www.baeldung.com/spring-security-custom-authentication-failure-handler