Spring CrudRepository .orElseThrow()

40,480

Solution 1

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

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

Solution 2

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.

Share:
40,480

Related videos on Youtube

szxnyc
Author by

szxnyc

Software engineer, tinkerer, curious, musician, and all around nice guy. Appreciates the front-end limelight of Web Programming but prefers the good old catacombs of back-end Server Side Development.

Updated on November 04, 2020

Comments

  • szxnyc
    szxnyc over 3 years

    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.");
      }
    }
    
  • timpham
    timpham almost 5 years
    @Eran can you explain this question? stackoverflow.com/questions/56180844/…