I cannot catch exceptions in method annotated @Transactional
.
I want to send mail to created user if save
operation succeded.
When username is already in use PostgreSQL throws exception PSQLException
which is extention of SQLExcpetion
which is extention of Exception
. I couldn't catch Exception
and PSQLException
then I tried to catch Throwable
and this is working, but not resolve my problem and come to that catching Throwable
is the cause of new problem.
When I get DataIntegrityViolationException (this is an excpetion from Spring) I want to propagate its because I have handler for my controller which returns statement and status specified for this concrete exception. And when I catch Throwable I have to throw always RuntimeException.
Very strange thing is that emailSender.sendEmail()
is called even if some exception was thrown. But if userRepository
is throwing an exception any method should not be called and exception should be caught in catch
statement and then transaction should be rollback. Do I correct understand transactions or not?
Implementation of my service:
@Transactional
public UserEntity createUser(UserEntity user) {
try {
final UserEntity saved = userRepository.save(user);
emailSender.sendEmail(saved);
return saved;
} catch (Throwable t) {
throw new RuntimeException();
}
return null;
}
Come to that when I try debug this method using IDEA, debugger doesn't enter catch statement, but my handlers annotated @RestControllerAdvice
are catching this exception.
Any idea what's wrong or maybe do you know similar questions?
Experienced the same issue. Fixed using saveAndFlush
.
This make sense because with transactional, transaction is being committed(to db) after executing the function. But with saveAndFlush
, it is not the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With