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.
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.
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.
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.
Method Summary Deletes the given entities in a batch which means it will create a single query. Deprecated.
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.
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