英文:
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<File> openFile(String fileName){
if (!fileExists(fileName)) {
return Optional.empty(() -> new RuntimeException("file " + fileName + " not found!"));
}
return Optinal.of(openFile(fileName));
}
// those calls of the method will throw the RuntimeException with detailed description
File openFile = openFile("notexistingfile.txt").get();
File openFile = openFile("notexistingfile.txt").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?
专注分享java语言的经验与见解,让所有开发者获益!
评论