I have the following method in my transactional service layer implemented with 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);
}
As you can see, in else if (userAccount.isExpired())
block, I want to first delete userAccount
and then throw an exception. But as it's throwing an exception, and exiting the method abruptly, the delete is not executed.
I wonder if there is any way to persist the delete action while throwing an exception.
I experienced same situation too.
My solution was using Spring Security FailureHandler
with this Class, you can make actions after Failure Event.
See Here, https://www.baeldung.com/spring-security-custom-authentication-failure-handler
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.