Skip to content
Advertisement

What is a good way to handle an Optional object returned by a Spring Data JPA repository in a situation like this?

I am working on a Spring Boot application. Into a service class I have this service method:

JavaScript

As usual it is calling the Spring Data JPA findById() method returning an Optional object.

I am returning the User object. And here I have the following doubt: if the Optional is empty, it is throwing an exception when I this operation is performed:

JavaScript

So now…what is the most common way to handle situation like this when I have a Optional object.

The previous service method is called into a controller method implementing an API, this one:

JavaScript

As you can see in my controller method I am checking if the result of the previous service is null, in case an exception will be thrown. This exception is handled by a class extenging ResponseEntityExceptionHandler in such a way to create a proper response.

So my idea was change my service method putting this retrievedUser.get() operation into a try catch. If I obtain the exception my getUserById() service method will return null and so my controller method will thrown the NotFoundException exception that will be handled returning a specific error response by Spring.

Could be a good solution or exist better way to handle situation like this?

Advertisement

Answer

I would return Optionals from the service then you could chain them real nicely like this:

JavaScript

And logging the warning should be handled in a common exception handler which logs all the Not Found’s similar way.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement