Spring MVC: Optional vs Exceptions in Service Layer

exception, option-type, service-layer, spring, spring-mvc

Solution

I guess this is more a matter of philosophy than programming.

For example, you have user logged in your system.

When you try to get user details `userService.getDetails(userId)`, you should throw exception (because you cannot have logged used without extra data about him) – this is error.

But if you try to get his friends `userService.getFriends(userId)`, it's OK if there aren't any records with given id. So Optional is good response in this case.

I think in this way.

Problem

I want to build a Service Layer handling Users. What is your suggestion to handle an invalid id. Returning with Optional or throw an Exception? The Service Layer is called by the Presentation Layer returning html views. Maybe also in regard to handling errors in the presentation layer? (Default Error Page, Logging,...) Optional ``` public Optional<User> findOne( Long id ) { try { User user = userRepository.findOne( id ); return Optional.ofNullable( user ); // something blow up in the Repository Layer } catch ( Exception ex ) { throw new ServiceException( ex ); } } ``` Exception ``` public User findOne( Long id ) { try { User user = userRepository.findOne( id ); // something blow up in the Repository Layer } catch ( Exception ex ) { throw new ServiceException( ex ); } if ( user == null ) throw new ServiceException( "Invalid Id" ); return user; } ```

Original source