Spring CrudRepository .orElseThrow()

szxnyc picture szxnyc · Nov 4, 2014 · Viewed 26.4k times · Source

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.");
  }
}

Answer

Eran picture Eran · Nov 4, 2014

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

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