空的 Optional,带有自定义的描述性异常

huangapple 未分类评论53阅读模式
英文:

empty Optional with custom descriptive exception

问题

以下是您要翻译的内容:

我正在寻找一种方法,以返回空的Optional对象信息,说明为什么它为空,并提供详细信息以供进一步调查。如果要求Optional的消费者期望它不为空,那么最好能够传递异常供应商(exception supplier)到Optional.empty方法中,以指定默认异常,以便在抛出异常时使用。
类似于:

Optional<File> openFile(String fileName) {
    if (!fileExists(fileName)) {
        return Optional.empty(() -> new RuntimeException("文件 " + fileName + " 未找到!"));
    }
    return Optional.of(openFile(fileName));
}

// 对该方法的这些调用将抛出带有详细描述的RuntimeException
File openFile = openFile("notexistingfile.txt").get();
File openFile = openFile("notexistingfile.txt").orElseThrow();

我知道可以使用带有异常供应商的orElseThrow,但那么每次调用都应在方法外部执行。是否有可行的策略来实现这一点?

英文:

I'm looking for a way to return with empty Optional object information why it is empty and details for further investigation. It will be nice to have exception supplier to be passed to Optional.empty method to specify default exception to be thrown if consumer of the optional expects it not to be empty.
Something like:

Optional&lt;File&gt; openFile(String fileName){
    if (!fileExists(fileName)) {
        return Optional.empty(() -&gt; new RuntimeException(&quot;file &quot; + fileName + &quot; not found!&quot;));
    }
    return Optinal.of(openFile(fileName));
}

// those calls of the method will throw the RuntimeException with detailed description
File openFile = openFile(&quot;notexistingfile.txt&quot;).get();
File openFile = openFile(&quot;notexistingfile.txt&quot;).orElseThrow();

I know about orElseThrow with exception supplier, but then it should be done outside of the method for each call.
Is there there viable strategy to do this?

huangapple
  • 本文由 发表于 2020年3月15日 16:41:56
  • 转载请务必保留本文链接:https://java.coder-hub.com/60691077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定