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."); } }
Try passing a lambda expression of type Supplier<MeetingDoesNotExistException>
:
Meeting meeting = meetingRepository.findByMeetingId(meetingId) .orElseThrow(() -> new MeetingDoesNotExistException(meetingId));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With