java - 重构 orElseThrow block 以返回 RuntimeException

标签 java java-8

我有下面的 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/

相关文章:

java - DatagramChannel 接收可能不会返回 SocketAddress

java - 如何通过 FileOutputStream 在网页内容中创建新文件

java - CompletableFuture#异常地重新抛出已检查的异常

java - 在不使用反射的情况下使用相同的 getters 泛化第三方类

android - 订阅后一次性对象为空

java - 从 Spring Boot 资源执行和处理 Void @Async 操作

java - 忽略合并映射中的重复键

java - 使用 JDK8 : 时,LogManager.getLogger 使应用程序停止约 10-30 秒

Java 8 - Collections.groupingBy 结果顺序

java - 未找到资源异常