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