我有下面的findProductBetweenPriceRange()
方法,它抛出BadRequestException
,如下所示:
public Product findProductBetweenPriceRange(int price1, int price2) {
Optional<Product> product = productService.findProductBetween(price1, price2);
return product.orElseThrow(() -> {
String debugInfo = "price1="+price1+";price2="+price2;
throw new BadRequestException("No Product found for price range",debugInfo);
});
}
BadRequestException类:
public final class BadRequestException extends RuntimeException {
public BadRequestException(String errorMessage, String debugInfo) {
this.errorMessage = errorMessage;
this.debugInfo = debugInfo;
}
//fields & getters
}
上面的代码工作正常,但是,我只想将
orElseThrow()
块重构为另一种方法,如下所示。我尝试创建
throwBadRequestException()
的方法throws
BadRequestException
&我从orElseThrow()
调用它,但我遇到了类似的错误,“不存在类型变量的实例,因此void符合” 。
public Product findProductBetweenPriceRange(int price1, int price2) {
Optional<Product> product = productService.findProductBetween(price1, price2);
return product.orElseThrow(() -> throwBadRequestException(price1, price2));
}
private void throwBadRequestException(int price1, int price2) {
String debugInfo = "price1="+price1+";price2="+price2;
throw new BadRequestException("No Product found for price range", debugInfo);
}
我清楚地知道
BadRequestException
是一个未经检查的异常,因此编译器无法找到该方法引发所需的异常。为了仔细检查,我还尝试使用BadRequestException
子句将throws
添加到方法签名中,以提示编译器,但是没有运气。所以,问题是,有什么方法可以将
orElse
块很好地重构为一个单独的方法并抛出RuntimeException
(即BadRequestException
)? 最佳答案
只需return
和BadRequestException
就可以了。void
基本上是导致此问题的原因。 orElseThrow
使用供应商,而不是功能。
因此,您需要修改以下代码:
public Product findProductBetweenPriceRange(int price1, int price2) {
Optional<Product> product = productService.findProductBetween(price1, price2);
return product.orElseThrow(() -> throwBadRequestException(price1, price2));
}
private BadRequestException throwBadRequestException(int price1, int price2) {
String debugInfo = "price1="+price1+";price2="+price2;
return new BadRequestException("No Product found for price range", debugInfo);
}