Chris Garsonn
Chris Garsonn

Reputation: 777

How to do Java Optional if present do something or else throw?

What I want to do is, updating a customer if it is present but if there is no customer then throw an exception. But I could not find the correct stream function to do that. How can I achieve this ?

public Customer update(Customer customer) throws Exception {
        Optional<Customer> customerToUpdate = customerRepository.findById(customer.getId());
        customerToUpdate.ifPresentOrElse(value -> return customerRepository.save(customer),
        throw new Exception("customer not found"));
    }

I could not return the value coming from save function because it is saying that it is void method and not expecting return value.

Upvotes: 1

Views: 9848

Answers (1)

MC Emperor
MC Emperor

Reputation: 22977

As Guillaume F. already said in the comments, you could just use orElseThrow here:

Customer customer = customerRepository.findById(customer.getId())
    .orElseThrow(() -> new Exception("customer not found"));
return customerRepository.save(customer);

By the way, avoid throwing Exception, as that exception is too broad. Use a more specific type, like NotFoundException.

Upvotes: 6

Related Questions