Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot catch exceptions in method annotated @Transactional

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.

  1. 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.

  2. 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?

like image 963
user Avatar asked Dec 04 '17 15:12

user


1 Answers

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.

like image 182
Vinujan.S Avatar answered Nov 13 '22 16:11

Vinujan.S