我有下面的 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()
block 重构为不同的方法,如下所示。
我尝试创建 throwBadRequestException()
方法,该方法 throw
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
是一个未经检查的异常,因此编译器无法发现该方法抛出所需的异常。为了仔细检查,我还尝试使用 throws
子句将 BadRequestException
添加到方法签名中以提示编译器,但没有成功。
所以,问题是有什么方法可以将 orElse
block 很好地重构为一个单独的方法并抛出 RuntimeException
(即 BadRequestException
) ?
最佳答案
因此,只需返回
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);
}
关于java - 重构 orElseThrow block 以返回 RuntimeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48912604/