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

Time:04-13

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.

CodePudding user response:

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.

CodePudding user response:

public Comment getCommentById(long id) {
        Optional<Comment> optional = commentRepository.findById(id);
        Comment comments = null;
        if(optional.isPresent()){
            comments = optional.get();
        }else{
            throw new RuntimeException("Post not found for id :: "   id);
        }
        return comments;
    }

Above is the code snippet from one of my project you can try in this way.

  • Related