在空流中抛出异常的优雅方式



我正在获取客户端列表。然后我将enity映射到dto并返回结果。我想在空的客户端列表上抛出异常,但也希望避免代码中的if语句。

我可以将列表包装成可选的,但我相信还有更优雅的解决方案。

Set<ClientDto> clients = Optional.of(repo.findByNumber(number))
.filter(CollectionUtils::isNotEmpty)
.orElseThrow(() -> new NotFoundException())
.stream()
.map(client -> new ClientDto(client.getName()))
.collect(Collectors.toSet());

有更清洁的解决方案吗?因为在我的代码中几乎没有usless链。我甚至现在开始认为纯粹的if会更可读。

我不知道如何使用纯流来实现这一点,但您可以定义一个方法,该方法返回列表的流,并在其为空时抛出异常。

private <T> Stream<T> throwIfEmpty(List<T> list) {
if(list.isEmpty()) {
throw new IllegalArgumentException("List must not be empty");
}
return list.stream();
}

那么你可以通过以下方式使用它:

List<Client> clients = throwIfEmpty(repo.findByNumber(number))
.map(client -> new ClientDto(client.getName()))
.collect(Collectors.toSet());

也许这个解决方案会让你高兴:(

最新更新