Donatello
Donatello

Reputation: 353

How to handle exceptions using EntityManager in Spring Boot

I have dao layer:

@Transactional
public class DatabaseCollectionDao implements IDatabaseCollectionDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void create(Collection collection) {
           entityManager.persist(collection);
    }
}

It works correctly but:

  1. When database isn't available I have SocketException.
  2. When database contains a duplicate key I have SQLIntegrityConstraintViolationException

I am trying to try/catch it inside create method:

@Override
    public void create(Collection collection) {
           try{
               entityManager.persist(collection);
           } catch (SQLIntegrityConstraintViolationException e){
               //do smth
           }
    }

But Intellij says that It is never thrown.
When I try to try/catch Exception i have UnexpectedRollbackException.

How to handle exceptions using JPA entityManager?

update: An attempt to remove @Transactional gave nothing

P.S. To be sure i tried to try/catch it in higher layers. I don't know what i can try more to solve it.

Upvotes: 0

Views: 1153

Answers (1)

sankar
sankar

Reputation: 278

create customException handler extend ResponseEntityExceptionHandler . @ExceptionHandler(ConstraintViolationException::class) fun handleConstraintViolation(ex: ConstraintViolationException, request: WebRequest): ResponseEntity {} this kotlin snippet u can convert to java easily –

Upvotes: 1

Related Questions