Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The return value of "orElseThrow" must be used

Tags:

When I am scanning code with sonar lint the following code shows the bug as "The return value of "orElseThrow" must be used"

itemList.stream()
    .filter(item -> orderItemId.equals(item.getId()))
    .findAny()
    .orElseThrow(() -> new BadRequestException("12345","Item Not Found"));

This is just for a validation purpose no need to return anything from this statement. need to validate whether the item exists or not.

FYI: Eclipse showing a quick fix as squid:S2201

Anybody have any idea how to resolve this bug?

like image 368
Baji Shaik Avatar asked Mar 28 '18 10:03

Baji Shaik


Video Answer


1 Answers

I'm assuming this is a warning (not using the value returned by orElseThrow() shouldn't be an error).

If you wish to eliminate that warning, use isPresent() instead:

if (!itemList.stream().filter(i->orderItemId.equals(i.getId())).findAny().isPresent()) {
    throw new BadRequestException("12345","Item Not Found");
}

or just avoid using Optionals, and use anyMatch() instead:

if (!itemList.stream().anyMatch(i->orderItemId.equals(i.getId()))) {
    throw new BadRequestException("12345","Item Not Found");
}
like image 179
Eran Avatar answered Sep 20 '22 14:09

Eran