Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NoSuchElementException a good alternative for ResourceNotFoundException?

Before Spring-Boot and Spring-Data 2.0, I used org.springframework.boot.context.config.ResourceNotFoundException to check if a instance of entity was in the database. I used the following exception handler in a controller:

@ExceptionHandler(ResourceNotFoundException.class)
public HttpStatus handleNotFoundResource() {
    return HttpStatus.NOT_FOUND;
}

Now, because repository methods return an optional, I used java.util.NoSuchElementException to do the job in the controller:

@ExceptionHandler(NoSuchElementException.class)
public HttpStatus handleNotFoundResource() {
    return HttpStatus.NOT_FOUND;
}

Is it the best practice?

like image 905
banan3'14 Avatar asked Oct 23 '25 16:10

banan3'14


1 Answers

NoSuchElementException is much broader than your custom exception ResourceNotFoundException that you define to be thrown in a specific case : no entity/resource in the database.
Between the controller and the repository layer you can have other method invocations that throw NoSuchElementException (Collection methods, other Optional and still many others) other than Repository.findXXX().get().

So your idea may create undesirable side effects.
To prevent any regression, you should handle explicitly the Optional unwrapping such as return Optional.orElseThrown(ResourceNotFoundException::new).
If you want to generalize it you could introduce a base class for your repository that does this processing.

like image 78
davidxxx Avatar answered Oct 26 '25 07:10

davidxxx