如果Optional& lt;& LT;则抛出异常价值存在 [英] Throw exception if Optional<> value is present

查看:64
本文介绍了如果Optional& lt;& LT;则抛出异常价值存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Spring Data Repository方法.

Suppose I have a Spring Data Repository method.

Optional<Branch> findByName(@Nonnull final String name);

如果我发现此方法执行有任何价值,我的业务逻辑就会抛出异常.

My business logic is such if I find any value for this method execution I would throw an exception.

例如,我可以这样做:

Optional.of(branchRepository.findByName(branch.getName()))
                .filter(bo -> !bo.isPresent())
                .orElseThrow(NameNotAvailableException::new);

或另一种方式:

Optional.of(branchRepository.findByName(branch.getName()))
                .filter(Optional::isEmpty)
                .orElseThrow(NameNotAvailableException::new);

在这种情况下,我不确定使用过滤器是否合适,因为我的方法返回 Optional< Branch> 没有清单.似乎在JDK中,如果有ifPresentThrow()方法可用,那将达到我的目的.

I am not sure if using filter, in this case, is appropriate as my method returns Optional<Branch> not a list. It seems that if in JDK if there were ifPresentThrow() method was available that would serve my purpose.

是的,可以使用我不希望使用的命令式代码来编写此代码.所以我的问题是,是否可以实现PresentThrow()或以一种更好的方式以函数样式进行操作是一样的事情.预先感谢.

推荐答案

您最好使用"exists".

You'd better use "exists".

if (repository.existsByName(branchName)) {
    throw ...
}

它更有用,因为它不会从db中检索对象,而只是对/错.

It more usefull, because it doesn't retrive the object from db, just true/false.

这篇关于如果Optional&amp; lt;&amp; LT;则抛出异常价值存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆