如果数据库查询返回空,抛出异常的正确方法是什么?我正在尝试使用.orElseThrow()
方法,但无法编译:
Meeting meeting = meetingRepository.findByMeetingId(meetingId).orElseThrow(new MeetingDoesNotExistException(meetingId));
编译器说:
使用lambda表达式可以做到这一点吗?
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.");
}
}
最佳答案
尝试传递Supplier<MeetingDoesNotExistException>
类型的lambda表达式:
Meeting meeting =
meetingRepository.findByMeetingId(meetingId)
.orElseThrow(() -> new MeetingDoesNotExistException(meetingId));