Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Repository Cannot Catch EntityNotFoundException

I want to throw a custom error class when a user searches my repo with an invalid ID. This should be very straight forward, but I cannot seem to catch any errors thrown by JpaRepository. I have made several attempts to solve this, but the following is my most straight forward attempt:

try {
    Object obj = repository.getOne(id)
}
catch (EntityNotFoundException e) {
    throw CustomException("message");
}

When running this in a debugger, repository throws the exact exception I am expecting javax.persistence.EntityNotFoundException, but the code simply skips over my catch statement and the function returns with an error.

I tried using repository.findById(id) with similar results. I also tried catching Exception and Throwable. Any ideas? I will add more information to my post if it ends up my problem is not immediately obvious.

like image 915
Keifer Avatar asked Apr 11 '18 21:04

Keifer


People also ask

How do I fix EntityNotFoundException?

Combining @NotFound(action = NotFoundAction. IGNORE) with @ManyToOne annotation will stop the persistence provider from throwing the EntityNotFoundException, but we'll have to handle missing entity by hand to avoid NullPointerException.

How does spring boot handle EntityNotFoundException?

Create a method called handleEntityNotFound() and annotate it with @ExceptionHandler , passing the class object EntityNotFoundException. class to it. This declaration signalizes Spring that every time EntityNotFoundException is thrown, Spring should call this method to handle it.

Which is better CrudRepository or JpaRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

Is JpaRepository deprecated?

Method Summary Deletes the given entities in a batch which means it will create a single query. Deprecated.


1 Answers

getOne() is just a wrapper for EntityManager.getReference(). That method will not throw any exception.

It returns an uninitialized proxy, assuming that the entity indeed exists. It doesn't get the entity state from the database, and thus doesn't even know if it exists. It assumes it does.

You'll only get an exception later, if you try to access the state of the entity.

Use findById()/findOne(), check if you get a non-empty/non-null result (because these methods don't throw any exception if the entity doesn't exist, they return empty or null), and throw your exception if that's the case.

like image 196
JB Nizet Avatar answered Oct 29 '22 11:10

JB Nizet