25

What is the proper way to throw an exception if a database query returns empty? I'm trying to use the .orElseThrow() method but it won't compile :

Meeting meeting = meetingRepository.findByMeetingId(meetingId).orElseThrow(new MeetingDoesNotExistException(meetingId));

The compiler is saying :

"he method orElseThrow(Supplier) in the type Optional is not applicable for the arguments (MeetingRestController.MeetingDoesNotExistException)

Is it possible to do this with lambda expressions?

CrudRepository :

import java.util.Optional;

import org.springframework.data.repository.CrudRepository;

public interface MeetingRepository extends CrudRepository<Meeting, Long>{
    Optional<Meeting> findByMeetingId(Long id);
}

Exception :

@ResponseStatus(HttpStatus.CONFLICT) // 409
class MeetingDoesNotExistException extends RuntimeException{
  public MeetingDoesNotExistException(long meetingId){
    super("Meeting " + meetingId + " does not exist.");
  }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
szxnyc
  • 2,495
  • 5
  • 35
  • 46

2 Answers2

66

Try passing a lambda expression of type Supplier<MeetingDoesNotExistException> :

Meeting meeting = 
    meetingRepository.findByMeetingId(meetingId)
                     .orElseThrow(() -> new MeetingDoesNotExistException(meetingId));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • @Eran can you explain this question? https://stackoverflow.com/questions/56180844/spring-data-jpa-restcontroller-repository-optional-strange-behavior – timpham May 17 '19 at 20:53
3

The error means what it says.

The documentation for orElseThrow states that it takes a Supplier as a parameter.

You have stated your exception is a RuntimeException, which is not a Supplier. Therefore, orElseThrow() is not applicable to that argument type. You would have to pass it a Supplier, not a RuntimeException.

It would be simpler syntax to use a lambda expression.

Jason C
  • 38,729
  • 14
  • 126
  • 182