how use in Java method .or and .orElseThrow

45 Views Asked by At

Is even possible add more method inside of
findbyId(id).orElseThrow(() -> new BusinessException("bug"));

and not just Exception ? so something like

.orElseThrow(() -> { //do something here new BusinessException("bug") });

or use ".or" method where I can put more methods, I don't need Exceptions. So if doesn't exist then //do this // and this

because with classic method you add Entity as a Optional,then check in condition if isPresent and then if not, you can do couple more thing in else{}

1

There are 1 best solutions below

2
dan1st might be happy again On

I am not sure whether I understand you correctly and assume you want to add additional logic to orElseThrow for the first part.

Add additional logic to orElseThrow

orElseThrow always throws an exception and that exception is taken from the lambda.

If you want to add functionality before throwing the exception, make sure to return it:

yourOptional
    .orElseThrow(() -> {
        //additional logic possible here
        //will be executed if optional is empty
        return new YourException();
    });

However, if you want to add logic that decides whether or not to throw an exception, you can use or to map to an optional containing the value to return that is empty if you want to throw the exception. Then, use orElseThrow:

yourOptional
    .or(() -> {
        //additional logic possible here
        //will be executed if optional is empty
        if(shouldThrow()){
            return Optional.empty();
        }
        return Optional.of(someValue);//if you originally had an Optional<T>, someValue should be assignable to T
    })
    .orElseThrow(() -> {
        return new YourException();
    });

no exception

In case you don't want to throw an exception but have some other logic, you can use orElseGet.
This method just executes a lambda expression if the Optional is empty and returns the result:

yourOptional
    .orElseGet(() -> {
        //this will be executed if the Optional is empty
        return someValue;
    });