Refactor orElseThrow block to return a RuntimeException

I have a method findProductBetweenPriceRange()that throws BadRequestExceptionas shown below:

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);
    });
}

Class BadRequestException:

public final class BadRequestException extends RuntimeException {

    public BadRequestException(String errorMessage, String debugInfo) {
        this.errorMessage = errorMessage;
        this.debugInfo = debugInfo;
    }

    //fields & getters
}

The above code works fine, but I just wanted to reorganize the block orElseThrow()to another method, as shown below.

I tried to create a method throwBadRequestException()that throws BadRequestException, and I call it from orElseThrow(), but I ran into an error such as "there is no instance of a type variable, so void matches . "

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)?

+4
2

, 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);
}
+5

Java-8 BiFunction .

private BiFunction<String, String, BadRequestException> badReqExceptionSupplier = (msg, info) -> new BadRequestException(msg, info);

, :

throw badReqExceptionSupplier.apply("No Product found for price range",debugInfo);
+3

Source: https://habr.com/ru/post/1693937/


All Articles